work092.java
package test05;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class work092
{
public static void main(String[] args)
{
List<String> list1 = new ArrayList<>(); //元素可重复
list1.add("a");
list1.add("b");
list1.add("c");
list1.add("d");
list1.add("a");
list1.add("b");
list1.add("c");
list1.add("d");
int i = (int)(Math.random() * list1.size());
System.out.println("随机获取数组中的元素:" + list1.get(i));
list1.remove(2);
System.out.println("移除索引为2后,数组中的元素:");
for (int j = 0; j < list1.size(); j++)
{
System.out.print(list1.get(j) + " ");
}
System.out.println();
List<String> list2 = new LinkedList<>(); //元素可重复
list2.add("aa");
list2.add("bb");
list2.add("cc");
list2.add("dd");
list2.add("aa");
list2.add("bb");
list2.add("cc");
list2.add("dd");
int index = (int)(Math.random() * list2.size());
System.out.println("随机获取数组中的元素:" + list2.get(index));
list2.remove(1);
System.out.println("移除索引1后,数组中元素为:");
for (int j = 0; j < list2.size(); j++)
{
System.out.print(list2.get(j) + " ");
}
}
}
work093.java
package test05;
import java.util.Iterator;
import java.util.TreeSet;
public class work093 implements Comparable<Object>
{
private String name;
private long id;
public work093(String name,long id)
{
this.name = name;
this.id = id;
}
public int compareTo(Object obj)
{
work093 stu1 = (work093)obj;
int result;
if (this.id > stu1.id)
{
result = 1;
}
else if (this.id == stu1.id)
{
result = 0;
}
else
{
result= -1;
}
return result;
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
public long getId()
{
return this.id;
}
public void setId(long id)
{
this.id = id;
}
public static void main(String[] args)
{
work093 stu1 = new work093("张龙", 01011); //八进制数
work093 stu2 = new work093("赵虎", 01021);
work093 stu3 = new work093("王朝", 01051);
work093 stu4 = new work093("马汉", 01012);
TreeSet<work093> tree1 = new TreeSet<>();
tree1.add(stu1);
tree1.add(stu2);
tree1.add(stu3);
tree1.add(stu4);
Iterator<work093> iterator1 = tree1.iterator();
System.out.println("set集合中的所有元素:");
while (iterator1.hasNext())
{
work093 temp = (work093) iterator1.next();
System.out.println("id:" + temp.getId() + " name:" + temp.getName());
}
iterator1 = tree1.headSet(stu2).iterator(); //截取排在stu2之前的集合
System.out.println("截取前面部分的集合:");
while (iterator1.hasNext())
{
work093 temp = (work093) iterator1.next();
System.out.println("id:" + temp.getId() + " name:" + temp.getName());
}
iterator1 = tree1.subSet(stu2, stu3).iterator();
System.out.println("截取中间部分的集合:");
while (iterator1.hasNext())
{
work093 temp = (work093) iterator1.next();
System.out.println("id:" + temp.getId() + " name:" + temp.getName());
}
}
}