java开发中的List的使用

Java容器类包含List、ArrayList、Vector及map、HashTable、HashMap
ArrayList和HashMap是异步的,Vector和HashTable是同步的,所以Vector和HashTable是线程安全的,而 ArrayList和HashMap并不是线程安全的。因为同步需要花费机器时间,所以Vector和HashTable的执行效率要低于 ArrayList和HashMap。
List是有序的Collection,使用此接口能够精确的控制每个元素插入的位置。用户能够使用索引(元素在List中的位置,类似于数组下标)来访问List中的元素,这类似于Java的数组。
和下面要提到的Set不同,List允许有相同的元素。
除了具有Collection接口必备的iterator()方法外,List还提供一个listIterator()方法,返回一个 ListIterator接口,和标准的Iterator接口相比,ListIterator多了一些add()之类的方法,允许添加,删除,设定元素, 还能向前或向后遍历。
实现List接口的常用类有LinkedList,ArrayList,Vector和Stack。
ArrayList类
ArrayList实现了可变大小的数组。它允许所有元素,包括null。ArrayList没有同步。
size,isEmpty,get,set方法运行时间为常数。但是add方法开销为分摊的常数,添加n个元素需要O(n)的时间。其他的方法运行时间为线性。
每个ArrayList实例都有一个容量(Capacity),即用于存储元素的数组的大小。这个容量可随着不断添加新元素而自动增加,但是增长算法 并没有定义。当需要插入大量元素时,在插入前可以调用ensureCapacity方法来增加ArrayList的容量以提高插入效率。
和LinkedList一样,ArrayList也是非同步的(unsynchronized)。

如果定义了一个List , 想要比较List里面的内容, 我们需要重写类中和hastcode方法和equals 方法 .
重写hascode方法是比较简单的,或者说是个模式性的东西 , 只需要在类中添加一个 public int hashCode()方法 ,并将类中的所有变量进行一个序列化即可.
如:
public int hashCode()
{
return Name.hashCode()*11+method.hashCode()*7+start;
}
注: 其中的变量Name 、method是String类型的变量, 而start则是int型. 这三个变量是这个类中定义的三个私的有变量.
重写 public int hashCode()方法也是一个固定的模式
如:
public boolean equals (Object obj)
{
if (this == obj)
return true;
if ((obj == null) || !(obj.getClass() == this.getClass()))
return false;
Location other = (Location) obj;
return this.Name.equals(other.className)
&& this.method.equals(other.methodName)
&& this.start==(other.startLine)
}
注:Location是这个类的名字, 把这个程序完整的放到一个类中可以表示为:
public class Location
{
:
private String Name = null;
private String method = null;
private int start = -1;
:
:
public List getMeaasge()
{
List message = new ArrayList();
:
:

//判断加到list的内容是否有与Location同名的对外对象, 如果想等则要加入
if(!message .contains(methLoca))
// 如果不在程序重写hascode方法和equal方法则这个判断是无效的
message .add(methLoca);

return message
}


public int hashCode()
{
return Name.hashCode()*11+method.hashCode()*7+start;
}

public boolean equals (Object obj)
{
if (this == obj)
return true;
if ((obj == null) || !(obj.getClass() == this.getClass()))
return false;
Location other = (Location) obj;
return this.Name.equals(other.className)
&& this.method.equals(other.methodName)
&& this.start==(other.startLine)
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值