出于练习目的,我正在尝试在不使用 java 集合的情况下实现我自己的 ArrayList。在这个阶段我想实现两个主要方法,add(E) 和 get(int) tp 明白了。我的代码如下。但是我遇到了一些问题:
- “return (E) myData[index]”行发出警告“类型安全:未检查的从对象到 E 的转换”。我该如何解决这个问题
- ArrayList.add(T) 的 Java 7 实现,返回一个 boolean 值。在什么情况下 add() 必须返回 false。它在什么逻辑下返回 false,什么时候返回 true?
- 哪里可以找到java 7实现ArrayList的源码
附言。请不要只回答问题 3 并向我推荐一和二的蔗糖代码!
import java.util.Arrays;
public class MyArrayList<E>{
private final int DEFAULT_SIZE=2;
private Object[] myData = new Object[DEFAULT_SIZE];
private int actSize=0;
public boolean add(E data){
if (actSize>=myData.length/2){
increaseSize();
}
myData[actSize++] = data;
return true;//when can it be false?
}
private void increaseSize()throws RuntimeException{
myData = Arrays.copyOf(myData, myData.length*2);
}
public E get(int index) throws RuntimeException{
if (index >= actSize){
throw new IndexOutOfBoundsException();
}
return (E) myData[index];
}
public static void main(String[] args) {
MyArrayList<String> arList = new MyArrayList<>();
arList.add("Hello");
arList.add("Bye bye!");
System.out.println(arList.get(1));// prints Bye bye! which is correct
}
}
最佳答案
The line "return (E) myData[index]" issues warning "Type safety: Unchecked cast from Object to E". How can I address that
抑制警告
@SuppressWarnings("unchecked")
The Java 7 implementation of
ArrayList.add(T)
returns aboolean
. Under what circumstances theadd()
has to returnfalse
. Under what logic it returnfalse
and when returnstrue
?
参见 javadoc
Returns:
true
(as specified byCollection.add(E)
)
它总是返回 true
。
Where can I find the source code of java 7 implementation of ArrayList
在您的 JDK 安装的 src.zip
存档中或通过简单搜索在线找到它
java ArrayList source code
关于java - 不使用集合实现自己的 ArrayList<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22752206/