总结
步骤
1.数据来源 集合
2.集合转Object数组
3.Object数组转String数组
流程
Set——》Object[]——》String[]
问题
上面的步骤有点繁琐 能不能不需要Object[]到String[]的转换?可以 使用AbstractCollection.toArray(集合)。这种解决方法 把第三步省了。
代码
package test;
import java.util.HashSet;
import java.util.Set;
public class SetToArray {
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("gzh");
Object[] objects = set.toArray(); //得到Object数组
System.out.println(objects);
//
String[] strings = new String[set.size()]; //1.得到数组的大小:set.size()
set.toArray(strings);//2.直接得到String数组 不需要手工把Object转String
System.out.println(strings);
}
}
复制代码
步骤
Set
1.准备数据Set
2.从Set得到Object[]
集合.toArray()。//返回值是Object[]
3.从Object.toString()得到String类型数据的数组
List
1.准备数据List
2.从List得到Object[]
3.从Object.toString()得到String类型数据的数组
总结
1.Set和List的实现步骤一样
2.toArray()的源码实现不一样
1)Set是基于迭代器
2)List是基于Array.copyOf()
3.AbstractCollection类很重要 是个基础类 它的toArray()方法是一个集合和数组互转的中介
HashSet源码分析
在集合和数组之间有个中介类 就像流的字节和字符之间也有一个中介类 实现它们之间的互转。
类的方法官方介绍
This method acts as bridge between array-based and collection-based APIs.
代码 HashSet继承了AbstractCollection
/**
* This class provides a skeletal implementation of the <tt>Collection</tt>
* interface, to minimize the effort required to implement this interface. <p>
*
* To implement an unmodifiable collection, the programmer needs only to
* extend this class and provide implementations for the <tt>iterator</tt> and
* <tt>size</tt> methods. (The iterator returned by the <tt>iterator</tt>
* method must implement <tt>hasNext</tt> and <tt>next</tt>.)<p>
*
* To implement a modifiable collection, the programmer must additionally
* override this class's <tt>add</tt> method (which otherwise throws an
* <tt>UnsupportedOperationException</tt>), and the iterator returned by the
* <tt>iterator</tt> method must additionally implement its <tt>remove</tt>
* method.<p>
*
* The programmer should generally provide a void (no argument) and
* <tt>Collection</tt> constructor, as per the recommendation in the
* <tt>Collection</tt> interface specification.<p>
*
* The documentation for each non-abstract method in this class describes its
* implementation in detail. Each of these methods may be overridden if
* the collection being implemented admits a more efficient implementation.<p>
*
* This class is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @author Josh Bloch
* @author Neal Gafter
* @see Collection
* @since 1.2
*/
public abstract class AbstractCollection<E> implements Collection<E> { //list和set都继承了Collection类
/**
* {@inheritDoc}
*
* <p>This implementation returns an array containing all the elements
* returned by this collection's iterator, in the same order, stored in
* consecutive elements of the array, starting with index {@code 0}.
* The length of the returned array is equal to the number of elements
* returned by the iterator, even if the size of this collection changes
* during iteration, as might happen if the collection permits
* concurrent modification during iteration. The {@code size} method is
* called only as an optimization hint; the correct result is returned
* even if the iterator returns a different number of elements.
*
* <p>This method is equivalent to:
*
* <pre> {@code
* List<E> list = new ArrayList<E>(size());
* for (E e : this)
* list.add(e);
* return list.toArray();
* }</pre>
*/
public Object[] toArray() {
// Estimate size of array; be prepared to see more or fewer elements
Object[] r = new Object[size()]; //size()调用子类方法
Iterator<E> it = iterator(); //迭代器方法调用子类方法
for (int i = 0; i < r.length; i++) { //索引
if (! it.hasNext()) // fewer elements than expected
return Arrays.copyOf(r, i);
r[i] = it.next(); //遍历。保存到数组。数组的元素类型是Object。如果想要得到String类型的数据 还需要使用Object.toString()方法得到字符串类型数据。
}
return it.hasNext() ? finishToArray(r, it) : r;
}
复制代码
迭代器方法调用的是HashMap里的方法 最终是sun包里的类。
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
{
private final class KeySet extends AbstractSet<K> {
public Iterator<K> iterator() {
return newKeyIterator();
}
public int size() {
return size;
}
public boolean contains(Object o) {
return containsKey(o);
}
public boolean remove(Object o) {
return HashMap.this.removeEntryForKey(o) != null;
}
public void clear() {
HashMap.this.clear();
}
}
// Subclass overrides these to alter behavior of views' iterator() method
Iterator<K> newKeyIterator() {
return new KeyIterator(); //sun包里的类
}
复制代码
ArrayList源码分析
代码
/**
* Returns an array containing all of the elements in this list
* in proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this list in
* proper sequence
*/
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
复制代码