#集合(collection)学习#
三种增、删、改、查的操作
#ArrayList()
package collection;
import java.util.ArrayList;
import java.util.Iterator;
public class CollectionTest01
{
public static void main(String[] args)
{
ArrayList list = new ArrayList();
// 增
list.add(2);
list.add(10);
list.add("lizheng");
// 删
// list.remove(0); 优先匹配
// list.clear();
// 改
// list.set(0, "李政");
// 查--------遍历
/*简单for循环
* for (int index = 0; index < list.size(); index++)
* {
* System.out.println(list.get(index));
* }
*/
/*增强for循环
* for (Object ele : list)
* {
* System.out.println(ele);
* }
*/
// iterator迭代器
Iterator iterator = list.iterator();
while (iterator.hasNext())
{
System.out.println(iterator.next());
}
}
}
HashSet()
package collection;
import java.util.HashSet;
public class CollectionTest02
{
public static void main(String[] args)
{
HashSet hs = new HashSet();
// 增
hs.add(1);
hs.add("lizheng");
hs.add(5);
// 删 ----- 匹配值
// hs.remove(1);
// 查 ---- 遍历
for (Object ele : hs)
{
System.out.println(ele);
}
}
}
TreeMap
package collection;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
public class CollectionTest03
{
public static void main(String[] args)
{
TreeMap tm = new TreeMap();
// 增 改(后面的会覆盖前面的)
tm.put("中国男足", "海参");
tm.put("中国女足", "冠军");
tm.put("中国男足", "垃圾");
// 查 遍历
Set keySet = tm.keySet();
Iterator iterator = keySet.iterator();
while (iterator.hasNext())
{
Object key = iterator.next();
System.out.println(key + "=" + tm.get(key));
}
}
}
集合用法有很多,但规律差不多,这里只练习了三个,初学,发现问题,欢迎留言!!!