package Work;
import java.util.*;
import org.junit.Test;
class Student{
int score;
Student(int i){
this.score=i;
}
public String toString() {
return String.valueOf(score);
}
}
public class test {
@Test
public void testArrayList(){
ArrayList<Integer> list = new ArrayList<Integer>();
//查看arraylist长度
System.out.println(list.size());
//增加元素
list.add(3);
list.add(5);
list.add(100);
list.add(5);
list.add(100);
System.out.println(list.size());
//获取特定位置的元素
System.out.println(list.get(1));
//删除元素
System.out.println(list.remove(1));
//打印整个arraylist
System.out.println(list);
//更新特定位置元素
list.set(0,10000);
//遍历
System.out.println("------------------");
for(int i:list){
System.out.println(i);
}
//将arraylist装换成相应的数组
Integer[] array=new Integer[list.size()];
array= list.toArray(array);
System.out.println("------------------");
//当然arralist存放的数据类型还可以是自己定义的类
Iterator<Integer> a = list.iterator();
while(a.hasNext()){
System.out.println(a.next());
}
System.out.println("------------------");
}
@Test
public void testHashSet(){
HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(21);
set.add(322);
set.add(334);
set.add(544);
set.add(6);
//不能存储相同的元素
set.add(6);
//不是按照顺序存储
System.out.println(set);
//遍历
System.out.println("------------------");
Iterator<Integer> a = set.iterator();
while(a.hasNext()){
System.out.println(a.next());
}
System.out.println("------------------");
//HashSet必须要有一个comparator类,才能往里添加自定义对象,否则会抛出ClassCastException?是这样的吗
}
@Test
public void testHashSetAddObiect(){
HashSet<Student> set = new HashSet<Student>();
set.add(new Student(1));
set.add(new Student(2));
set.add(new Student(2));
System.out.println(set);
}
@Test
public void testHashMap(){
// 构造一个hashmap对象
HashMap<String, String> map1 = new HashMap<>();
// 往hashmap中添加数据,如果key重复,则会覆盖
map1.put("1", "白百合");
map1.put("1", "马蓉");
// 继续添加
map1.put("2", "王宝强");
map1.put("3", "黄渤");
map1.put("4", "靳东");
map1.put("5", null);
// 获取map中的数据
String a = map1.get("3");
// System.out.println(a);
// 获取map的长度
int size = map1.size();
System.out.println(size);
// 从map中移除数据
String remove = map1.remove("3");
System.out.println(remove);
// 判断数据是否存在
// 方法1:再去get那个移掉的key,看是否还能获取到value
String b = map1.get("5");
System.out.println(b);
// 方法2:可以利用map的contains功能判断指定的key是否存在
boolean c = map1.containsKey("5"); // 此方法才能真正确定map中是否存在指定的key
System.out.println(c);
// hashmap的遍历:
Set<String> keySet = map1.keySet();
for(String a1:keySet){
System.out.println(map1.get(a1));
}
}
public static void main(String args[]){
//数组、arrlist、hashset都能够用for来遍历。for var:aaaaa
}
}
hashmap、hashset、arraylist用法示例代码
猜你喜欢
转载自blog.csdn.net/m0_37719047/article/details/88547708
今日推荐
周排行