有什么方法可以将对象变成数组吗?

问题描述 投票:0回答:1

我正在做这个狂欢编程,它想要将某些东西实现到 MyLinkedList 中 我想我已经明白了它的要点,但我仍然无法弄清楚,狂欢希望我使用这个:https://liveexample.pearsoncmg.com/test/Exercise24_01_13e.txt

我试图实现的方法是 addAll、removeAll、retainAll、containsAll、toArray() 和 toArray(T[])

import java.util.*;

public class Exercise24_01 {
  public static void main(String[] args) {
    new Exercise24_01();
  }

  public Exercise24_01() {
    Scanner input = new Scanner(System.in);
    String[] name1 = new String[5];
    String[] name2 = new String[5];
    String[] name3 = new String[2];
    System.out.print("Enter five strings for array name1 separated by space: ");
    for (int i = 0; i < 5; i++) {
      name1[i] = input.next();
    }
    
    System.out.print("Enter five strings for array name2 separated by space: ");
    for (int i = 0; i < 5; i++) {
      name2[i] = input.next();
    }

    System.out.print("Enter two strings for array name3 separated by space: ");
    for (int i = 0; i < 2; i++) {
      name3[i] = input.next();
    }
    
    MyList<String> list1 = new MyArrayList<>(name1);   
    MyList<String> list2 = new MyArrayList<>(name2);   
    System.out.println("list1: " + list1);
    System.out.println("list2: " + list2);
    list1.addAll(list2);
    System.out.println("After addAll: list1 is " + list1 + "\n");
    
    list1 = new MyArrayList<>(name1);
    list2 = new MyArrayList<>(name2);   
    System.out.println("list1: " + list1);
    System.out.println("list2: " + list2);
    list1.removeAll(list2);
    System.out.println("After removeAll: list1 is " + list1 + "\n");
    
    list1 = new MyArrayList<>(name1);
    list2 = new MyArrayList<>(name2);   
    System.out.println("list1: " + list1);
    System.out.println("list2: " + list2);
    list1.retainAll(list2);
    System.out.println("After retainAll: list1 is " + list1 + "\n");
    
    list1 = new MyArrayList<>(name1);
    list2 = new MyArrayList<>(name2);   
    System.out.println("list1: " + list1);
    System.out.println("list2: " + list2);
    list1.retainAll(list2);
    System.out.println("list1 contains all list2? " + list1.containsAll(list2) + "\n");
    
    list1 = new MyArrayList<>(name1);
    list2 = new MyArrayList<>(name3);
    System.out.println("list1: " + list1);
    System.out.println("list2: " + list2);
    System.out.println("list1 contains all list2? " + list1.containsAll(list2) + "\n");
    
    Object[] name4 = list1.toArray();
    System.out.print("name4: ");
    for (Object e: name4) {
      System.out.print(e + " ");
    }
    
    String[] name5 = new String[list1.size()];
    String[] name6 = list1.toArray(name5);
    System.out.print("\nname6: ");
    for (Object e: name6) {
      System.out.print(e + " ");
    }
  }
}

class MyArrayList<E> implements MyList<E> {
    public static final int INITIAL_CAPACITY = 16;
    private E[] data = (E[])new Object[INITIAL_CAPACITY];
    private int size = 0; // Number of elements in the list

    /** Create an empty list */
    public MyArrayList() {
    }

    /** Create a list from an array of objects */
    public MyArrayList(E[] objects) {
      for (int i = 0; i < objects.length; i++)
        add(objects[i]); // Warning: don't use super(objects)! 
    }

    @Override /** Add a new element at the specified index */
    public void add(int index, E e) {   
      ensureCapacity();

      // Move the elements to the right after the specified index
      for (int i = size - 1; i >= index; i--)
        data[i + 1] = data[i];

      // Insert new element to data[index]
      data[index] = e;

      // Increase size by 1
      size++;
    }

    /** Create a new larger array, double the current size + 1 */
    private void ensureCapacity() {
      if (size >= data.length) {
        E[] newData = (E[])(new Object[size * 2 + 1]);
        System.arraycopy(data, 0, newData, 0, size);
        data = newData;
      }
    }

    @Override /** Clear the list */
    public void clear() {
      data = (E[])new Object[INITIAL_CAPACITY];
      size = 0;
    }

    @Override /** Return true if this list contains the element */
    public boolean contains(Object e) {
      for (int i = 0; i < size; i++)
        if (e.equals(data[i])) return true;

      return false;
    }

    @Override /** Return the element at the specified index */
    public E get(int index) {
      checkIndex(index);
      return data[index];
    }

    private void checkIndex(int index) {
      if (index < 0 || index >= size)
        throw new IndexOutOfBoundsException
          ("Index: " + index + ", Size: " + size);
    }
    
    @Override /** Return the index of the first matching element 
     *  in this list. Return -1 if no match. */
    public int indexOf(Object e) {
      for (int i = 0; i < size; i++)
        if (e.equals(data[i])) return i;

      return -1;
    }

    @Override /** Return the index of the last matching element 
     *  in this list. Return -1 if no match. */
    public int lastIndexOf(E e) {
      for (int i = size - 1; i >= 0; i--)
        if (e.equals(data[i])) return i;

      return -1;
    }

    @Override /** Remove the element at the specified position 
     *  in this list. Shift any subsequent elements to the left.
     *  Return the element that was removed from the list. */
    public E remove(int index) {
      checkIndex(index);
      
      E e = data[index];

      // Shift data to the left
      for (int j = index; j < size - 1; j++)
        data[j] = data[j + 1];

      data[size - 1] = null; // This element is now null

      // Decrement size
      size--;

      return e;
    }

    @Override /** Replace the element at the specified position 
     *  in this list with the specified element. */
    public E set(int index, E e) {
      checkIndex(index);
      E old = data[index];
      data[index] = e;
      return old;
    }

    @Override
    public String toString() {
      StringBuilder result = new StringBuilder("[");

      for (int i = 0; i < size; i++) {
        result.append(data[i]);
        if (i < size - 1) result.append(", ");
      }

      return result.toString() + "]";
    }

    /** Trims the capacity to current size */
    public void trimToSize() {
      if (size != data.length) { 
        E[] newData = (E[])(new Object[size]);
        System.arraycopy(data, 0, newData, 0, size);
        data = newData;
      } // If size == capacity, no need to trim
    }

    @Override /** Override iterator() defined in Iterable */
    public java.util.Iterator<E> iterator() {
      return new ArrayListIterator();
    }
   
    private class ArrayListIterator 
        implements java.util.Iterator<E> {
      private int current = 0; // Current index 

      @Override
      public boolean hasNext() {
        return (current < size);
      }

      @Override
      public E next() {
        return data[current++];
      }

      @Override
      public void remove() {
        if (current == 0) // next() has not been called yet
          throw new IllegalStateException(); 
        MyArrayList.this.remove(--current);
      }
    }
    
    @Override /** Return the number of elements in this list */
    public int size() {
      return size;
    }
}

interface MyList<E> extends java.util.Collection<E> {
  // WRITE YOUR CODE HERE
  /** Add a new element at the specified index in this list */
  public void add(int index, E e);

  /** Return the element from this list at the specified index */
  public E get(int index);

  /** Return the index of the first matching element in this list.
   *  Return -1 if no match. */
  public int indexOf(Object e);

  /** Return the index of the last matching element in this list
   *  Return -1 if no match. */
  public int lastIndexOf(E e);

  /** Remove the element at the specified position in this list
   *  Shift any subsequent elements to the left.
   *  Return the element that was removed from the list. */
  public E remove(int index);

  /** Replace the element at the specified position in this list
   *  with the specified element and returns the new set. */
  public E set(int index, E e);
  
  @Override /** Add a new element at the end of this list */
  public default boolean add(E e) {
    add(size(), e);
    return true;
  }

  @Override /** Return true if this list contains no elements */
  public default boolean isEmpty() {
    return size() == 0;
  }
  
  @Override /** Remove the first occurrence of the element e 
   *  from this list. Shift any subsequent elements to the left.
   *  Return true if the element is removed. */
  public default boolean remove(Object e) {
    if (indexOf(e) >= 0) {
      remove(indexOf(e));
      return true;
    }
    else
      return false;
  }

  @Override
  public default boolean containsAll(Collection<?> c) {
    // Left as an exercise
    boolean containE;
    for (E e: c) {
      if (contains(c)) {
        containE = true;
      } else {
        containE = false;
      }
    }
    if (containE != true) {
      return false;
    }
    return true;
  }

  @Override
  public default boolean addAll(Collection<? extends E> c) {
    // Left as an exercise
    boolean addE;
    for (E e : c) {
      if (add(e)) {
        addE = true;
      } else {
        addE = false;
      }
    }
    if (addE != true) {
      return false;
    }
    return true;
  }

  @Override
  public default boolean removeAll(Collection<?> c) {
    // Left as an exercise
    boolean removeE;
    for (E e : c) {
      if (remove(e)) {
         removeE = true;
      } else {
        removeE = false;
      }
    }
    if (removeE != true) {
      return false;
    }
    return true;
  }
  @Override
  public default boolean retainAll(Collection<?> c) {
    // Left as an exercise
    boolean retainE;
    for (E e : c) {
      if (retain(e)) {
        retainE = true;
      } else {
        retainE = false;
      }
    }
    if (retainE != true) {
      return false;
    }
    return true;
  }

  @Override
  public default Object[] toArray() {
    // Left as an exercise
    Object[] array = new Object[]();
    for (int i = 0; i < array.length(); i++) {
      Object[i] = array[i];
    }
    return null;
  }

  @Override
  public default <T> T[] toArray(T[] array) {
    // Left as an exercise
    for (E element : array) {
    System.out.println(element);
    }
    System.out.println();
    return null;
  }
}

但出来的只有这个:

 ----jGRASP exec: javac -g --module-path C:\Users\rmeri\Downloads\openjfx-19_windows-x64_bin-sdk\javafx-sdk-19\lib --add-modules=javafx.controls -Xlint:unchecked Exercise24_01.java
Exercise24_01.java:361: error: array dimension missing
    Object[] array = new Object[]();
                                 ^
1 error

 ----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.

如果有人可以帮助我,我将非常感激,但默认方法无法更改。

java arrays arraylist linked-list jgrasp
1个回答
0
投票

正确的数组声明看起来更像这样:

Object[] array = new Object[]{};
- 我认为你结合了 ArrayList 和数组声明。 (ArrayList 的声明看起来更像是:
ArrayList<>() array = new ArrayList<>();

顺便说一句,尝试查看错误消息并尝试自己解码!学习如何阅读错误消息对于解决问题非常重要! 希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.