list取出遵循放入顺序,set取出不遵循放入顺序
作者:互联网
package com.pp.listAndSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.naming.ldap.SortControl;
public class MainClass {
public static void main(String[] args) {
// List<Integer> list = new ArrayList<Integer>();
// list.add(1);
// list.add(2);
// list.add(3);
// for(Integer l:list) {
// System.out.println(l);
// }
System.out.println("-------------");
// Set<Integer> set = new HashSet<Integer>();
// set.add(1);
// set.add(2);
// set.add(3);
// set.add(4);
// set.add(5);
Person p0 = new Person("a", 1);
Person p1 = new Person("b", 1);
Person p2 = new Person("c", 1);
Person p3 = new Person("d", 1);
int a = p0.hashCode();
int b = p1.hashCode();
int c = p2.hashCode();
int d = p3.hashCode();
System.out.println("a.hashCode():" + p0.hashCode());
System.out.println("b.hashCode():" + p1.hashCode());
System.out.println("c.hashCode():" + p2.hashCode());
System.out.println("d.hashCode():" + p3.hashCode());
int[] arr = { a, b, c, d };
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
List<Person> list = new ArrayList<Person>();
list.add(p0);
list.add(p1);
list.add(p2);
list.add(p3);
for (Person p : list) {
System.out.println(p.toString());
}
System.out.println("---------------------");
Set<Person> set = new HashSet<Person>();
set.add(p0);
set.add(p1);
set.add(p2);
set.add(p3);
Iterator<Person> it = set.iterator();
while (it.hasNext()) {
System.out.println(it.next().toString());
}
}
}
-------------
a.hashCode():366712642
b.hashCode():1829164700
c.hashCode():2018699554
d.hashCode():1311053135
[366712642, 1311053135, 1829164700, 2018699554]
Person [name=a, age=1]
Person [name=b, age=1]
Person [name=c, age=1]
Person [name=d, age=1]
---------------------
Person [name=c, age=1]
Person [name=a, age=1]
Person [name=b, age=1]
Person [name=d, age=1]
给hashCode排序,发现set的取出也不遵循hashCode的大小顺序
标签:arr,顺序,list,hashCode,Person,add,set,遵循,放入 来源: https://blog.csdn.net/pb951028/article/details/94880852