TreeMap
默认按key升序排列
- floorKey(value): 返回小于或等于指定键元素value的最大键元素,否则返回null
- ceilingKey(value): 返回大于或等于指定键元素value的最小键元素,否则返回null
详情见题目:日程安排表
TreeSet
默认升序排序,可以返回满足要求的指定元素或指定集合;
正序遍历
for(Iterator iter = ts.iterator();iter.hasNext();)
{
System.out.println(iter.next());
}
倒序遍历
for(Iterator iter = ts.descendingIterator();iter.hasNext();)
{
System.out.println(iter.next());
}
TreeSet不支持快速随机遍历,只能通过迭代器遍历
- floor(value): 返回小于或等于指定元素value的最大元素,否则返回null
- ceiling(value): 返回大于或等于指定元素value的最小元素,否则返回null
- subSet(E start, boolean startInclusive, E end, boolean endInclusive): 返回区间start~end的集合 boolean变量决定区间的开闭
- headSet(E end, boolean endInclusive):返回小于(等于)end的区间
- tailSet(E start, boolean startInclusive):返回大于(等于)start的区间
TreeSet中的元素必须实现Comparable接口并重写compareTo()方法,以此判断元素是否重复,确定元素顺序。
如果存储自定义类,则需要在类中重写该方法
class 类名 implements Comparable<类名>{
public int compareTo(类名 that){
// 返回0时,二者相同,不会存储
// 返回正数时,按存储顺序取
// 返回负数时,按存储顺序倒序取
}
}
判顶两个对象是否重复:自定义类实现equal()和hashcode()
详情见题目:存在重复元素
与HashMap(HashSet)的区别:内部元素有序
HashMap
- putIfAbsent(key,value): 若不存在key,则加入hashmap,同put(key,value);若存在key,则hashmap不受影响,而put会重新覆盖
判顶两个自定义类对象是否重复:自定义类重写equal()和hashcode()
如果二者的name、sex、age同时相等则判定为二者相等:
@Override
public int hashCode() {
int result = name.hashCode();
result = 17 * result + sex.hashCode();
result = 17 * result + age.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Student)) {
//instanceof 已经处理了obj = null的情况
return false;
}
Student stuObj = (Student) obj;
// 地址相等
if (this == stuObj) {
return true;
}
// 如果两个对象姓名、年龄、性别相等,我们认为两个对象相等
if (stuObj.name.equals(this.name) && stuObj.sex.equals(this.sex) && stuObj.age.equals(this.age)) {
return true;
} else {
return false;
}
}
详情见题目:最大频率栈
LinkedList
- 关于remove方法:
remove(int index):删除指定位置元素 例如:remove(9)
时间复杂度:O(1)
remove(Object o):删除某一元素 例如:remove(new Integer(9))
时间复杂度:O(n)
注意括号中变量类型:int和Integer不是同一类型,int是索引,Integer是对象
Iterator
Iterator<数据类型> it = XX.iterator();
while(it.hasNext())
//使用it.next() 遍历XX
String
substring
- public String substring(int beginIndex)
- public String substring(int beginIndex, int endIndex)
详情见题目:寻找最近的回文数