集合List的使用 (例子+概念)

集合List概念区:

List接口扩充了collection,所以拥有更多的方法,使用更方便,可以重复。实现子类ArrayList
具体使用看注释

集合List代码区:

import java.util.ArrayList;
import java.util.List;

public class ArrayListDemo {
	public static void main(String[] args) {
		// ArrayList<String> list1 = new ArrayList<String>();
		// 创建集合
		// list元素可以重复
		List<String> list1 = new ArrayList<String>();
		// Collection<String> c = new ArrayList<>();
		list1.add("张三");
		list1.add("李四");
		list1.add("王五");
		list1.add("张三");
		System.out.println(list1);

		List<User> list2 = new ArrayList<User>();
		list2.add(new User("老A", 23));
		list2.add(new User("老C", 24));
		list2.add(new User("老D", 12));
		list2.remove(new User("老A", 23));
		System.out.println(list2);

		List<String> list3 = new ArrayList<String>();
		list3.add("张XX");
		list3.add("赵");
		list3.addAll(1, list1);
		System.out.println(list3);
		list3.remove("赵");
		// 思考如何删除集合中自定义的对象实例(不用下标的方式)
		// list2.remove(new User("老A",23));
		list2.remove(0);
		System.out.println(list2);
		list3.remove(0);
		System.out.println(list3);
		//
		/*
		* for (int i = 0; i < list1.size(); i++) {
		* System.out.println(list1.get(i)); } for(String x:list1){
		* System.out.println(x); }
		*/


		// Object[] s = list1.toArray();


		String[] s = new String[3];
		s = list1.toArray(s);
		for (int i = 0; i < s.length; i++) {
			System.out.println(s[i]);
		}
	}
}

/*
 * class Util1{ public <T> T toArray1(T[] a,List<String> list){ int len =
 * list.size(); a = new T[len]; return null; } }
 */
class User {
	private String name;
	private int age;

	public User(String name, int age) {
		this.name = name;
		this.age = age;
	}

	@Override
	public String toString() {
		return "User [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;
		
		User other = (User) 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;
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值