Java学习笔记——集合

存储对象可以使用数组 (基本数据类型 & 引用数据类型) 和集合 (引用数据类型),用数组存储对象的弊端有:一旦创建,其长度不可变;数组中真正存储的对象个数不可知,除非自定义类。使用集合可以解决这些问题。

1 Java集合框架


JDK提供的集合API位于java.util包内。Java 集合可分为 Collection 和 Map 两种体系。

  • Collection (interface)

    JDK不提供此接口的任何直接实现,而是提供更具体的子接口 (如:Set和List) 实现。

    • List (interface):元素有序、可重复的集合(动态数组)。
      • ArrayList (主要实现类,首选)
      • LinkedList (对于频繁的插入、删除操作)
      • Vector (古老的实现类、线程安全的,但效率低于ArrayList)
    • Set (interface):元素无序、不可重复的集合。
      • HashSet (主要实现类)
        • LinkedHashSet
      • SortedSet (interface)
        • TreeSet
  • Map (interface):具有映射关系的 “key-value对” 的集合。

    • HashMap (主要实现类)
      • LinkedHashMap
    • SortedMap (interface)
      • TreeMap
    • Hashtable
      • Properties
  • Queue (interface)

对象排序接口:

  • Comparable
  • Comparator

容器工具类:

  • Collections

在 Java5 之前,Java 集合会丢失容器中所有对象的数据类型,把所有对象都当成 Object 类型处理;从 Java5 增加了泛型以后,Java 集合可以记住容器中对象的数据类型。

2 Collection接口API

方法摘要
booleanadd(E e) 确保此 collection 包含指定的元素(可选操作)。
booleanaddAll(Collection<? extends E> c) 将指定 collection 中的所有元素都添加到此 collection 中(可选操作)。
voidclear() 移除此 collection 中的所有元素(可选操作)。
booleancontains(Object o) 如果此 collection 包含指定的元素,则返回 true
booleancontainsAll(Collection<?> c) 如果此 collection 包含指定 collection 中的所有元素,则返回 true
booleanequals(Object o) 比较此 collection 与指定对象是否相等。
inthashCode() 返回此 collection 的哈希码值。
booleanisEmpty() 如果此 collection 不包含元素,则返回 true
Iterator<E>iterator() 返回在此 collection 的元素上进行迭代的迭代器。
booleanremove(Object o) 从此 collection 中移除指定元素的单个实例,如果存在的话(可选操作)。
booleanremoveAll(Collection<?> c) 移除此 collection 中那些也包含在指定 collection 中的所有元素(可选操作)。
booleanretainAll(Collection<?> c) 仅保留此 collection 中那些也包含在指定 collection 的元素(可选操作)。
intsize() 返回此 collection 中的元素数。
Object[]toArray() 返回包含此 collection 中所有元素的数组。
<T> T[]toArray(T[] a) 返回包含此 collection 中所有元素的数组;返回数组的运行时类型与指定数组的运行时类型相同。

增(add, addAll)、删(clear, remove, removeAll),size,contains、containsAll,equals,isEmpty

3 遍历

  • for循环

    Collection collection = new ArrayList();
    for (int i = 0; i < collection.size(); i++) {
        // 视情况而定
    }
    
  • 增强for循环

    for (Object obj: collection) {
        System.out.println(obj);
    }
    

    注意:改变obj不会改变原来集合中的值。

  • Iterator

    Iterator iterator = collection.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
    

    在调用it.next()方法之前必须要调用it.hasNext()进行检测。若不调用,且下一条记录无效,直接调用it.next()会抛出NoSuchElementException异常。

    Iterator 仅用于遍历集合,Iterator 本身并不提供承装对象的能力。如果需要创建 Iterator 对象,则必须有一个被迭代的集合。

4 List接口

List集合类中元素有序、且可重复,集合中的每个元素都有其对应的顺序索引。

要求List集合中的元素重写equals方法,才能适当地进行操作(如remove(Object obj)等)。

List 集合里添加了一些根据索引来操作集合元素的方法:

  • void add(int index, Object ele)
  • boolean addAll(int index, Collection eles)
  • Object get(int index)
  • int indexOf(Object obj)
  • int lastIndexOf(Object obj)
  • Object remove(int index)
  • protected void removeRange(int fromIndex, int toIndex)
  • Object set(int index, Object ele)
  • List subList(int fromIndex, int toIndex)

JDK API中List接口的实现类常用的有:ArrayList、LinkedList和Vector。

4.1 ArrayList

ArrayList 是线程不安全的,而 Vector 是线程安全的,即使为保证 List 集合线程安全,也不推荐使用Vector。

Arrays.asList(…) 方法返回的 List 集合既不是 ArrayList 实例,也不是 Vector 实例。 Arrays.asList(…) 返回值是一个固定长度的 List 集合。

  • JDK API 1.7
Modifier and TypeMethod and Description
booleanadd(E e) Appends the specified element to the end of this list.
voidadd(int index, E element) Inserts the specified element at the specified position in this list.
booleanaddAll(Collection<? extends E> c) Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator.
booleanaddAll(int index, Collection<? extends E> c) Inserts all of the elements in the specified collection into this list, starting at the specified position.
voidclear() Removes all of the elements from this list.
Objectclone() Returns a shallow copy of this ArrayList instance.
booleancontains(Object o) Returns true if this list contains the specified element.
voidensureCapacity(int minCapacity) Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
Eget(int index) Returns the element at the specified position in this list.
intindexOf(Object o) Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
booleanisEmpty() Returns true if this list contains no elements.
Iterator<E>iterator() Returns an iterator over the elements in this list in proper sequence.
intlastIndexOf(Object o) Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
ListIterator<E>listIterator() Returns a list iterator over the elements in this list (in proper sequence).
ListIterator<E>listIterator(int index) Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
Eremove(int index) Removes the element at the specified position in this list.
booleanremove(Object o) Removes the first occurrence of the specified element from this list, if it is present.
booleanremoveAll(Collection<?> c) Removes from this list all of its elements that are contained in the specified collection.
protected voidremoveRange(int fromIndex, int toIndex) Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
booleanretainAll(Collection<?> c) Retains only the elements in this list that are contained in the specified collection.
Eset(int index, E element) Replaces the element at the specified position in this list with the specified element.
intsize() Returns the number of elements in this list.
List<E>subList(int fromIndex, int toIndex) Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
Object[]toArray() Returns an array containing all of the elements in this list in proper sequence (from first to last element).
<T> T[]toArray(T[] a) Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
voidtrimToSize() Trims the capacity of this ArrayList instance to be the list’s current size.

4.2 LinkedList

对于频繁的插入或删除元素的操作,建议使用LinkedList类,效率较高。

新增方法:

  • void addFirst(Object obj)
  • void addLast(Object obj)
  • Object getFirst()
  • Object getLast()
  • Object removeFirst()
  • Object removeLast()

4.3* Vector

Vector 是一个古老的集合,JDK1.0就有了。大多数操作与ArrayList相同,区别之处在于Vector是线程安全的。

新增方法:

  • void addElement(Object obj)
  • void insertElementAt(Object obj,int index)
  • void setElementAt(Object obj,int index)
  • void removeElement(Object obj)
  • void removeAllElements()

在各种list中,最好把ArrayList作为缺省选择。当插入、删除频繁时,使用LinkedList;Vector总是比ArrayList慢,所以尽量避免使用。

4.4* ListIterator

List 额外提供了一个 listIterator() 方法,该方法返回一个 ListIterator 对象, ListIterator 接口继承了 Iterator 接口,提供了专门操作 List 的方法:

  • void add()
  • boolean hasPrevious()
  • Object previous()
  • Boolean hasNext()
  • Object next()

Iterator和ListIterator主要异同点:

  1. ListIterator和Iterator都有hasNext()和next()方法,可以实现顺序向后遍历。但是ListIterator有hasPrevious()和previous()方法,可以实现逆向(顺序向前)遍历。Iterator就不可以。
  2. ListIterator可以定位当前的索引位置,nextIndex()和previousIndex()可以实现。Iterator 没有此功能。
  3. ListIterator有add()方法,可以向List中插入对象,而Iterator不能。
  4. 都可实现删除对象,但是ListIterator可以实现对象的修改,set()方法可以实现。Iterator仅能遍历,不能修改。因为ListIterator的这些功能,可以实现对LinkedList等List数据结构的操作。

总结:

    • 都可以顺序向后遍历 (hasNext()和next()) 查
    • 都可以删除对象 (remove()) 删
    • ListIterator可以逆序遍历 (hasPrevious()和previous()) 查
    • ListIterator可以定位当前索引 (nextIndex()和previousIndex())
    • ListIterator可以插入数据 (add()) 增
    • ListIterator可以实现对象的修改 (set()) 改

即两者都有查、删;ListIterator多了增、改,加强了查。

5 Set接口

  1. 无序性:不等于随机性,无序性指的是元素在底层存储的位置是无序的。
  2. 不可重复性:不可添加Set中已有的元素。(要求添加进Set中的元素所在的类,一定要重写equals()和hashCode()方法,以保证Set元素的不可重复性)

5.1 HashSet

HashSet 按 Hash 算法来存储集合中的元素,因此具有很好的存取和查找性能。

当向 HashSet 集合中存入一个元素时,HashSet 会调用该对象的 hashCode() 方法来得到该对象的 hashCode 值,然后根据 hashCode 值决定该对象在 HashSet 中的存储位置。

HashSet 集合判断两个元素相等的标准:两个对象通过 hashCode() 方法比较相等,并且两个对象的 equals() 方法返回值也相等。重写hashCode()的原则是要尽量保证与equals()一致,即hashCode不同的两个对象,应不相等,hashCode相同,应相等。

5.2 LinkedHashSet

LinkedHashSet 是 HashSet 的子类,也是根据元素的 hashCode 值来决定元素的存储位置,但它同时使用链表维护元素的次序,这使得元素看起来是以插入顺序保存的。

LinkedHashSet插入性能略低于 HashSet(因为需要维护链表),但在迭代访问 Set 里的全部元素时有很好的性能。

5.3 TreeSet

TreeSet 是 SortedSet 接口的实现类,TreeSet 可以确保集合元素处于排序状态。

向TreeSet中添加的必须是同一个类的对象,并且这个类必须实现Comparable接口并实现compareTo(Object obj)方法(或使用Comparator),TreeSet中的两个对象通过该方法的返回值来比较大小。设计时应使hashCode、equals、compareTo或compare保持一致。

当向TreeSet中添加自定义类的对象时,有两种排序方法:①自然排序②定制排序

5.3.1 自然排序

TreeSet 会调用集合元素的 compareTo(Object obj) 方法来比较元素之间的大小关系,然后将集合元素按升序排列。

public class Person implements Comparable {
	private String name;
	private Integer age;
    
	...
        
	@Override
	public int compareTo(Object obj) {
		if (obj instanceof Person) {
			Person person = (Person) obj;
			int i = this.age.compareTo(person.getAge());
			if(i == 0) {
				return this.name.compareTo(person.getName());
			}
			return i;
		}
		return 0;
	}
	
}
5.3.2 定制排序

实现Comparator中的int compare(T o1,T o2)方法,比较o1和o2的大小:如果方法返回正整数,则表示o1大于o2;如果返回0,表示相等;返回负整数,表示o1小于o2。

将实现了Comparator接口的对象作为形参传递给TreeSet的构造器。

// 1.创建一个实现了Comparator接口的类对象
Comparator comparator = new Comparator() {
    @Override
    public int compare(Object o1, Object o2) {
        if (o1 instanceof Customer && o2 instanceof Customer) {
            Customer c1 = (Customer) o1;
            Customer c2 = (Customer) o2;
            int i = c1.getId().compareTo(c2.getId());
            if(i == 0) {
                return c1.getName().compareTo(c2.getName());
            }
            return i;
        }
        return 0;
    }
};
// 2.将此对象作为形参传递给TreeSet的构造器
TreeSet set = new TreeSet(comparator);
...

6 Map接口

Map与Collection并列存在。用于保存具有映射关系的数据: Key-Value。

Map 中的 key 和 value 可以是任何引用类型的数据。

Map 中的 key 用 Set 存放,对key的类的要求与Set中元素类似。

常用String类作为Map的“键”。

当后添加的元素的key值与已有的key重复时,后来的数据会覆盖原有的数据。

Modifier and TypeMethod and Description
voidclear() Removes all of the mappings from this map (optional operation).
booleancontainsKey(Object key) Returns true if this map contains a mapping for the specified key.
booleancontainsValue(Object value) Returns true if this map maps one or more keys to the specified value.
Set<Map.Entry<K,V>>entrySet() Returns a Setview of the mappings contained in this map.
booleanequals(Object o) Compares the specified object with this map for equality.
Vget(Object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
inthashCode() Returns the hash code value for this map.
booleanisEmpty() Returns true if this map contains no key-value mappings.
Set<K>keySet() Returns a Set view of the keys contained in this map.
Vput(K key, V value) Associates the specified value with the specified key in this map (optional operation).
voidputAll(Map<? extends K,? extends V> m) Copies all of the mappings from the specified map to this map (optional operation).
Vremove(Object key) Removes the mapping for a key from this map if it is present (optional operation).
intsize() Returns the number of key-value mappings in this map.
Collection<V>values() Returns a Collectionview of the values contained in this map.
  • 添加、删除操作:
    • Object put(Object key,Object value)
    • Object remove(Object key)
    • void putAll(Map t)
    • void clear()
  • 元视图操作的方法:
    • Set keySet()
    • Collection values()
    • Set entrySet()
  • 元素查询的操作:
    • Object get(Object key)
    • boolean containsKey(Object key)
    • boolean containsValue(Object value)
    • int size()
    • boolean isEmpty()
    • boolean equals(Object obj)

6.1 HashMap

HashMap 判断两个 key 相等的标准是:两个 key 通过 equals() 方法返回 true,hashCode 值也相等。
HashMap 判断两个 value相等的标准是:两个 value 通过 equals() 方法返回 true。

遍历
Map map = new HashMap();
map.put("AA", 213);
map.put("AB", 213);
map.put("BB", 456);
map.put(123, "CC");
map.put(null, null);
map.put(new Person("DD", 12), null);

// 遍历key集
Set set = map.keySet();
for(Object obj : set) {
    System.out.println(obj);
}

// 遍历value
Collection values = map.values();
for(Object obj : values) {
    System.out.println(obj);
}

// 遍历key-value
// 方式一
for(Object obj : set) {
    System.out.println(obj + ": " + map.get(obj));
}

// 方式二
Set entrySet = map.entrySet();
for(Object obj : entrySet) {
    Map.Entry entry = (Entry) obj;
    System.out.println(entry);
}

6.2 LinkedHashMap

与LinkedHashSet类似,使用链表维护添加进Map中的顺序,遍历Map时是按添加的顺序遍历的。

6.3 TreeMap

对key进行排序,对key的要求可参考TreeSet。

6.4* Hashtable

古老的 Map 实现类,线程安全,不允许使用 null 作为 key 和 value。不建议使用。

6.5 Properties

Hashtable 的子类,用于处理属性文件。

由于属性文件里的 key、value 都是字符串类型,所以 Properties 里的 key 和 value 都是字符串类型。

Properties properties = new Properties();
properties.load(new FileInputStream(new File("test.properties")));
System.out.println(properties.getProperty("user"));

7 Collections工具类

Collections 是一个操作 Set、List 和 Map 等集合的工具类。

Collections 中提供了一系列静态的方法对集合元素进行排序、查询和修改等操作,还提供了对集合对象设置不可变、对集合对象实现同步控制等方法。

  • 排序操作

    • reverse(List)
    • shuffle(List)
    • sort(List)
    • sort(List,Comparator)
    • swap(List,int, int)
  • 查找、替换

    • Object max(Collection)
    • Object max(Collection,Comparator)
    • Object min(Collection)
    • Object min(Collection,Comparator)
    • int frequency(Collection,Object)
    • void copy(List dest,List src)
    • boolean replaceAll(List list,Object oldVal,Object newVal)
  • 同步控制

    Collections 类中提供了多个 synchronizedXxx() 方法,该方法可使将指定集合包装成线程同步的集合,从而可以解决多线程并发访问集合时的线程安全问题。

Modifier and TypeMethod and Description
static <T> booleanaddAll(Collection<? super T> c, T... elements) Adds all of the specified elements to the specified collection.
static <T> Queue<T>asLifoQueue(Deque<T> deque) Returns a view of a Deque as a Last-in-first-out (Lifo) Queue.
static <T> intbinarySearch(List<? extends Comparable<? super T>> list, T key) Searches the specified list for the specified object using the binary search algorithm.
static <T> intbinarySearch(List<? extends T> list, T key, Comparator<? super T> c) Searches the specified list for the specified object using the binary search algorithm.
static <E> Collection<E>checkedCollection(Collection<E> c, Class<E> type) Returns a dynamically typesafe view of the specified collection.
static <E> List<E>checkedList(List<E> list, Class<E> type) Returns a dynamically typesafe view of the specified list.
static <K,V> Map<K,V>checkedMap(Map<K,V> m, Class<K> keyType, Class<V> valueType) Returns a dynamically typesafe view of the specified map.
static <E> Set<E>checkedSet(Set<E> s, Class<E> type) Returns a dynamically typesafe view of the specified set.
static <K,V> SortedMap<K,V>checkedSortedMap(SortedMap<K,V> m, Class<K> keyType, Class<V> valueType) Returns a dynamically typesafe view of the specified sorted map.
static <E> SortedSet<E>checkedSortedSet(SortedSet<E> s, Class<E> type) Returns a dynamically typesafe view of the specified sorted set.
static <T> voidcopy(List<? super T> dest, List<? extends T> src) Copies all of the elements from one list into another.
static booleandisjoint(Collection<?> c1, Collection<?> c2) Returns true if the two specified collections have no elements in common.
static <T> Enumeration<T>emptyEnumeration() Returns an enumeration that has no elements.
static <T> Iterator<T>emptyIterator() Returns an iterator that has no elements.
static <T> List<T>emptyList() Returns the empty list (immutable).
static <T> ListIterator<T>emptyListIterator() Returns a list iterator that has no elements.
static <K,V> Map<K,V>emptyMap() Returns the empty map (immutable).
static <T> Set<T>emptySet() Returns the empty set (immutable).
static <T> Enumeration<T>enumeration(Collection<T> c) Returns an enumeration over the specified collection.
static <T> voidfill(List<? super T> list, T obj) Replaces all of the elements of the specified list with the specified element.
static intfrequency(Collection<?> c, Object o) Returns the number of elements in the specified collection equal to the specified object.
static intindexOfSubList(List<?> source, List<?> target) Returns the starting position of the first occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.
static intlastIndexOfSubList(List<?> source, List<?> target) Returns the starting position of the last occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence.
static <T> ArrayList<T>list(Enumeration<T> e) Returns an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration.
static <T extends Object & Comparable<? super T>> Tmax(Collection<? extends T> coll) Returns the maximum element of the given collection, according to the natural ordering of its elements.
static <T> Tmax(Collection<? extends T> coll, Comparator<? super T> comp) Returns the maximum element of the given collection, according to the order induced by the specified comparator.
static <T extends Object & Comparable<? super T>> Tmin(Collection<? extends T> coll) Returns the minimum element of the given collection, according to the natural ordering of its elements.
static <T> Tmin(Collection<? extends T> coll, Comparator<? super T> comp) Returns the minimum element of the given collection, according to the order induced by the specified comparator.
static <T> List<T>nCopies(int n, T o) Returns an immutable list consisting of n copies of the specified object.
static <E> Set<E>newSetFromMap(Map<E,Boolean> map) Returns a set backed by the specified map.
static <T> booleanreplaceAll(List<T> list, T oldVal, T newVal) Replaces all occurrences of one specified value in a list with another.
static voidreverse(List<?> list) Reverses the order of the elements in the specified list.
static <T> Comparator<T>reverseOrder() Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
static <T> Comparator<T>reverseOrder(Comparator<T> cmp) Returns a comparator that imposes the reverse ordering of the specified comparator.
static voidrotate(List<?> list, int distance) Rotates the elements in the specified list by the specified distance.
static voidshuffle(List<?> list) Randomly permutes the specified list using a default source of randomness.
static voidshuffle(List<?> list, Random rnd) Randomly permute the specified list using the specified source of randomness.
static <T> Set<T>singleton(T o) Returns an immutable set containing only the specified object.
static <T> List<T>singletonList(T o) Returns an immutable list containing only the specified object.
static <K,V> Map<K,V>singletonMap(K key, V value) Returns an immutable map, mapping only the specified key to the specified value.
static <T extends Comparable<? super T>> voidsort(List<T> list) Sorts the specified list into ascending order, according to the natural ordering of its elements.
static <T> voidsort(List<T> list, Comparator<? super T> c) Sorts the specified list according to the order induced by the specified comparator.
static voidswap(List<?> list, int i, int j) Swaps the elements at the specified positions in the specified list.
static <T> Collection<T>synchronizedCollection(Collection<T> c) Returns a synchronized (thread-safe) collection backed by the specified collection.
static <T> List<T>synchronizedList(List<T> list) Returns a synchronized (thread-safe) list backed by the specified list.
static <K,V> Map<K,V>synchronizedMap(Map<K,V> m) Returns a synchronized (thread-safe) map backed by the specified map.
static <T> Set<T>synchronizedSet(Set<T> s) Returns a synchronized (thread-safe) set backed by the specified set.
static <K,V> SortedMap<K,V>synchronizedSortedMap(SortedMap<K,V> m) Returns a synchronized (thread-safe) sorted map backed by the specified sorted map.
static <T> SortedSet<T>synchronizedSortedSet(SortedSet<T> s) Returns a synchronized (thread-safe) sorted set backed by the specified sorted set.
static <T> Collection<T>unmodifiableCollection(Collection<? extends T> c) Returns an unmodifiable view of the specified collection.
static <T> List<T>unmodifiableList(List<? extends T> list) Returns an unmodifiable view of the specified list.
static <K,V> Map<K,V>unmodifiableMap(Map<? extends K,? extends V> m) Returns an unmodifiable view of the specified map.
static <T> Set<T>unmodifiableSet(Set<? extends T> s) Returns an unmodifiable view of the specified set.
static <K,V> SortedMap<K,V>unmodifiableSortedMap(SortedMap<K,? extends V> m) Returns an unmodifiable view of the specified sorted map.
static <T> SortedSet<T>unmodifiableSortedSet(SortedSet<T> s) Returns an unmodifiable view of the specified sorted set.

8 总结

  • List (有序<可用下标访问>、可重复)

    首选使用ArrayList,随机访问效率高;

    当频繁使用插入、删除操作时,使用LinkedList;

    Vector虽然线程安全,但效率较低,且Collections工具类能解决线程安全的问题,所以基本不使用Vector。

  • Set (无序、不可重复)

    Set会根据hashCode()和equals()方法判断两个元素是否相等(重复),所以放入Set的元素应重写这个方法,以达到期望的排除“重复”元素的效果。

    LinkedHashSet插入性能略低于 HashSet(因为需要维护链表),但在迭代访问 Set 里的全部元素时有很好的性能。遍历集合元素时,是按照添加进去的顺序实现的;频繁的遍历,较少的添加、插入操作建议选择。

    TreeSet是排序的集合,所以得有一个比较的操作,有两种方式现实,一种是实现Comparable并实现其中的compareTo方法,另一种是创建一个实现Comparator的类对象并将其作为实参传给TreeSet的构造器。

  • Map

    可用keySet(),values(),entrySet()对其进行遍历。

  • Collections

    一个用来操作集合的工具类,需要进行一些集合操作时可以考虑使用。

Collection可用Iterator遍历,List首选ArrayList,Set首选HashSet,Map首选HashMap。

List元素类该重写equals,Set元素类和Map的key所在类该重写equals和hashCode,TreeSet和TreeMap涉及到排序,所以还得有比较的操作。

此外,为解决元素存储的安全性问题,和读取数据时需要类型强转的问题,使代码更加健壮和简介,常使用泛型


注:以上笔记参考自尚硅谷

文件上传是Web开发中常见的功能之一,Java中也提供了多种方式来实现文件上传。其中,一种常用的方式是通过Apache的commons-fileupload组件来实现文件上传。 以下是实现文件上传的步骤: 1.在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> ``` 2.在前端页面中添加文件上传表单: ```html <form method="post" enctype="multipart/form-data" action="upload"> <input type="file" name="file"> <input type="submit" value="Upload"> </form> ``` 3.在后台Java代码中处理上传文件: ```java // 创建一个DiskFileItemFactory对象,用于解析上传的文件 DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置缓冲区大小,如果上传的文件大于缓冲区大小,则先将文件保存到临时文件中,再进行处理 factory.setSizeThreshold(1024 * 1024); // 创建一个ServletFileUpload对象,用于解析上传的文件 ServletFileUpload upload = new ServletFileUpload(factory); // 设置上传文件的大小限制,这里设置为10MB upload.setFileSizeMax(10 * 1024 * 1024); // 解析上传的文件,得到一个FileItem的List集合 List<FileItem> items = upload.parseRequest(request); // 遍历FileItem的List集合,处理上传的文件 for (FileItem item : items) { // 判断当前FileItem是否为上传的文件 if (!item.isFormField()) { // 获取上传文件的文件名 String fileName = item.getName(); // 创建一个File对象,用于保存上传的文件 File file = new File("D:/uploads/" + fileName); // 将上传的文件保存到指定的目录中 item.write(file); } } ``` 以上代码中,首先创建了一个DiskFileItemFactory对象,用于解析上传的文件。然后设置了缓冲区大小和上传文件的大小限制。接着创建一个ServletFileUpload对象,用于解析上传的文件。最后遍历FileItem的List集合,判断当前FileItem是否为上传的文件,如果是,则获取文件名,创建一个File对象,将上传的文件保存到指定的目录中。 4.文件上传完成后,可以给用户一个提示信息,例如: ```java response.getWriter().write("File uploaded successfully!"); ``` 以上就是使用Apache的commons-fileupload组件实现文件上传的步骤。需要注意的是,文件上传可能会带来安全隐患,因此在处理上传的文件时,需要进行严格的校验和过滤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值