集册 Java实例教程 处理空引用

处理空引用

欢马劈雪     最近更新时间:2020-01-02 10:19:05

565
处理空引用

import java.util.ArrayList;

import java.util.Collections;

import java.util.ListIterator;/** 来 自 时代Java - nowjava.com**/

import java.util.Objects;


class Item {

  private String name;

  private int partNumber;


  public Item() {

    this("Widget", 0);

  }


  public Item(String name, int partNumber) {

    this.name = Objects.requireNonNull(name);

    this.partNumber = partNumber;

  }


  public String getName() {

    return name;

  }
  /*
  来 自*
   时代Java公众号
  */


  public void setName(String name) {

    this.name = Objects.requireNonNull(name);

  }


  public int getPartNumber() {

    return partNumber;

  }


  public void setPartNumber(int partNumber) {

    this.partNumber = partNumber;

  }


  @Override

  public boolean equals(Object obj) {

    if (obj == null) {

      return false;

    }

    if (getClass() != obj.getClass()) {

      return false;

    }

    final Item other = (Item) obj;

    if (!Objects.equals(this.name, other.name)) {

      return false;

    }

    if (this.partNumber != other.partNumber) {

      return false;

    }

    return true;

  }


  @Override

  public int hashCode() {

    int hash = 7;

    hash = 47 * hash + Objects.hashCode(this.name);

    hash = 47 * hash + this.partNumber;

    return hash;

  }


  @Override

  public String toString() {

    return name + " - " + partNumber;

  }


}


public class Main {


  public static void main(String[] args) {

    Item item1 = new Item("Eraser", 2200);

    Item item2 = new Item("Eraser", 2200);

    Item item3 = new Item("Pencil", 1100);

    Item item4 = null;


    System.out.println("item1 equals item1: " + item1.equals(item1));

    System.out.println("item1 equals item2: " + item1.equals(item2));

    System.out.println("item1 equals item3: " + item1.equals(item3));

    System.out.println("item1 equals item4: " + item1.equals(item4));


    item2.setName(null);

    System.out.println("item1 equals item2: " + item1.equals(item2));


    // Additional Objects class methods

    item4 = null;

    System.out.println("toString: " + Objects.toString(item4));

    System.out.println("toString: " + Objects.toString(item4, "Item is null"));


    // Using empty iterators to avoid null pointer exceptions

    ListIterator<String> list = returnEmptyListIterator();

    while (list.hasNext()) {

      String item = list.next();

      System.out.printl
展开阅读全文