public MyArrayList() { array = (T[]) new Object[10]; size = 0; }
时间: 2024-05-31 21:13:07 浏览: 6
这段代码是一个泛型类MyArrayList的构造函数。在构造函数中,首先创建了一个大小为10的Object类型的数组array,然后通过强制类型转换将其转换为一个泛型类型T的数组。最后将size初始化为0,表示当前列表中没有元素。由于Java中的泛型擦除机制,实际上在运行时,T将被替换为Object类型。
相关问题
MyArrayList myArrayList = new MyArrayList(); myArrayList.add(1); myArrayList.add(2); myArrayList.add(3); myArrayList.display(); /*myArrayList.add(5); myArrayList.display();*/ try{ myArrayList.add(1,99); }catch (AddIndexOutOfException e) { e.printStackTrace(); } myArrayList.display(); }怎么给他横着打印
您可以将 `MyArrayList` 类中的 `display()` 方法进行修改,改为横向打印元素。以下是一种可能的实现方式:
```java
public void display() {
if (size == 0) {
System.out.println("[]");
return;
}
System.out.print("[");
for (int i = 0; i < size - 1; i++) {
System.out.print(elementData[i] + ", ");
}
System.out.println(elementData[size - 1] + "]");
}
```
这个实现方式在打印元素时,首先输出一个左中括号 `[`,然后依次输出每个元素和一个逗号 `,`,最后输出一个右中括号 `]`。这样就能够横向打印元素了。
定义一个泛型类MyArrayList,实现数组列表的基本操作: add、remove、get、size
```java
public class MyArrayList<T> {
private Object[] array;
private int size;
public MyArrayList() {
this.array = new Object[10];
this.size = 0;
}
public void add(T element) {
if (size == array.length) {
Object[] newArray = new Object[array.length * 2];
System.arraycopy(array, 0, newArray, 0, size);
array = newArray;
}
array[size++] = element;
}
public void remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
System.arraycopy(array, index + 1, array, index, size - index - 1);
array[--size] = null;
}
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return (T) array[index];
}
public int size() {
return size;
}
}
```
使用示例:
```java
MyArrayList<String> list = new MyArrayList<>();
list.add("foo");
list.add("bar");
list.add("baz");
System.out.println(list.get(1)); // 输出 "bar"
list.remove(0);
System.out.println(list.size()); // 输出 2
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)