有ArrayList,LinkedList,HashSet,TreeSet,HashMap,TreeMap六种集合的存储方式。
需要注意的是HashSet存储与TreeSet的存储方式。以下是测试代码,代码中有解析:
1、先编写一个用来创建对象的类Person
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59public class Person implements Comparable<Person>{ private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person(String name, int age) { super(); this.name = name; this.age = age; } public Person() { super(); } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public int compareTo(Person o) { // TODO Auto-generated method stub return this.getName().compareTo(o.getName());//按照字母名比较 } }
2、再编写测试类
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38public class Test { public static void main(String[] args) { Person p1 = new Person("胡苗青",10); System.out.println("-----ArrayList存储-----"); ArrayList<Person> al=new ArrayList<Person>(); al.add(p1); System.out.println(al+"n"); System.out.println("-----LinkedList存储-----"); LinkedList<Integer> ll = new LinkedList<Integer>(); ll.add(123); //123进行了自动装箱 System.out.println(ll+"n"); System.out.println("-----HashSet存储-----"); //HashSet存储自定义对象时,要求Person类重写hashCode()与equal()方法 HashSet<Person> hs = new HashSet<Person>(); hs.add(p1); System.out.println(hs+"n"); System.out.println("-----TreeSet存储-----"); //TreeSet存储自定义对象时,要求Person类具备比较规则,可以使内部比较器 可以是外部比较器 TreeSet<Person> ts=new TreeSet<Person>();//implements Comparable<Person> ts.add(p1); System.out.println(ts+"n"); System.out.println("-----HashMap存储-----"); //Map集合采用键值对的存储方式 HashMap<Person,String> hm = new HashMap<Person,String>(); hm.put(p1, p1.getName()); System.out.println(hm+"n"); System.out.println("-----TreeMap存储-----"); TreeMap<Person,Integer> tm = new TreeMap<Person,Integer>(); tm.put(p1, p1.getAge()); System.out.println(tm); } }
最后
以上就是纯真白羊最近收集整理的关于java深化——各种类型的集合 存储方式的总结代码的全部内容,更多相关java深化——各种类型的集合内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复