Java书写示例equals(),hashCode(),compareTo(),clone(),StringBuilder(),list删除元素等

来源:互联网 发布:自由基地军品服饰 淘宝 编辑:程序博客网 时间:2024/04/28 09:39

equals()

实现equals()
参数必须是Object,而不能是外围类
覆盖equals()时,也要覆盖相应的hashCode(),与equals(),保持一致
另外注意String的默认值是null

public class Person {private String name;private int birthYear;byte[] raw;@Overridepublic boolean equals(Object o){if(this == o){return true;}if(!(o instanceof Person)){return false;}Person other = (Person)o;return StringUtils.equals(name, other.name)&& birthYear == other.birthYear&& Arrays.equals(raw, other.raw);}public static void main(String args[]){Person p = new Person();Person p2 = new Person();System.out.println(p.equals(p2));}}

hashCode()

hashCode()最简单的合法实现就是简单地return 0;虽然这个实现是正确的,但是这会导致HashMap这些数据结构运行得很慢。
注意如果如果a或b未赋值会产生java.lang.NullPointerException
public class Person {private String a;private Object b;private byte c;int [] d;@Overridepublic int hashCode(){return a.hashCode() + b.hashCode() + c + Arrays.hashCode(d);}
public static void main(String[] args) {Person p = new Person();Person p1 = new Person();HashMap map = Maps.newHashMap();map.put(p,"hi");map.put(p1,"hi2");System.out.println(map);System.out.println(map.get(p));System.out.println(map.get(p1));//System.out.println(p.hashCode());}}

CompareTo()

给出2条
public class Person implements Comparable<Person>{private String firstName;private String lastName;private int birthdate;@Overridepublic int compareTo(Person other){int comparison = firstName.compareTo(other.firstName);if(comparison == 0){comparison = lastName.compareTo(other.lastName);}if(comparison == 0){comparison = birthdate - other.birthdate;}return comparison;}}
或者
public class Interval implements Comparable{    private int start;    private int end; @Override    public boolean equals(Object o) {        if (!(o instanceof Intervalable)) {            return false;        }        Intervalable other = (Intervalable)o;        return this.start == other.getStart() &&               this.end == other.getEnd();    }    @Override    public int hashCode() {        return this.start % 100 + this.end % 100;    }    @Override    public int compareTo(Object o) {        if (!(o instanceof Intervalable)) {            return -1;        }        Intervalable other = (Intervalable)o;        int comparison = this.start - other.getStart();        return comparison != 0 ? comparison : this.end - other.getEnd();    }}

clone()

public class Values implements Cloneable {private String abc;private  double foo;private int[] bars;private Date hired;@Overridepublic Object clone() throws CloneNotSupportedException{Values result = (Values)super.clone();result.bars = result.bars.clone();result.hired = (Date) result.hired.clone();return result;}}

StringBuilder链接字符串

public static String join(List<String> strs, String separator){StringBuilder sb = new StringBuilder();boolean first = true;for(String s : strs){if(first)first = false;else sb.append(separator);sb.append(s);}return sb.toString();}public static String join1(List<String> strs, String separator){StringBuilder sb = new StringBuilder();int len = strs.size();for(int i = 0; i < len - 1; i++){sb.append(strs.get(i));sb.append(separator);}sb.append(strs.get(len - 1));return sb.toString();}public static void main(String[] args) {List<String> strs = Lists.newArrayList("a" , "b" , "c" , "d");String s = join1(strs, ",");System.out.println(s);}

Random获得随机整数

public static final Random rand = new Random();public static int diceRoll(){return rand.nextInt(100) + 1;}public static void main(String[] args) {int n = 5000;HashMap<Integer, Integer> map = Maps.newHashMap();while(n-- > 0){int r = diceRoll();if(map.containsKey(r)){map.put(r, map.get(r) + 1);continue;}map.put(r, 1);}System.out.println(map.toString().replace(", ", "\n"));}
List删除元素
public static void main(String args[]){Student s = new Student("a",1);Student s2 = new Student("b",2);Student s3 = new Student("c",3);Student s4 = new Student("d",3);Student s5 = new Student("e",3);List<Student> list = Lists.newArrayList(s,s2,s3,s4,s5);test5(list);}/** * 不可以 * 会报java.util.ConcurrentModificationException */public static void test1(List<Student> list){for(Student st: list){if(st.getAge() == 3){list.remove(st);}}}/** * 可以 */public static void test2(List<Student> list){for(int i = 0; i< list.size(); i++){if(list.get(i).getAge() == 3){list.remove(i);i--;}}}/** * 可以 */public static void test3(List<Student> list){Iterator<Student> iterator = list.iterator();while(iterator.hasNext()){Student st = iterator.next();if(st.getAge() == 3){iterator.remove();}}}/** * 可以 */public static void test4(List<Student> list){List<Student> delteList = Lists.newArrayList();for(Student st: list){if(st.getAge() == 3){delteList.add(st);}}list.removeAll(delteList);}/** * 可以 */public static void test5(List<Student> list){for(Iterator<Student> iterator = list.iterator();iterator.hasNext();){Student st = iterator.next();if(st.getAge() == 3){iterator.remove();}}}


0 0
原创粉丝点击