Search code examples
javaarraysarraylistdynamic-arrays

Java - Add and remove elements from a dynamic array/list


I need my array to be dynamic, as long as the user enters/deletes elements. The array can't have the length already defined or ask the user the length. For example the user decides to add 5, the array would be: {5}, then the user adds 34 {5,34}, then deletes 5, {34}. Is there a way of doing it? i've been trying with list but when i used if the remove one didn't work and when i use switch with this code it says "unreachable statement". Here's the code so far:

List<String> list = new ArrayList<>();
        Scanner stdin = new Scanner(System.in);

        do {
            System.out.println("Current  " + list);
            System.out.println("Add more? (1) delete one? (2) exit (3)");
            int a= stdin.nextInt();  
            
            switch(a){
                case 1:
                System.out.println("Enter: ");
                list.add(stdin.next()); 
                break;
                case 2:
                System.out.println("Enter: ");
                list.remove(stdin.next());
                break;
                case 3:
                break;
                default:
                break;
            }
            
        } while (true);
        
        stdin.close();
        System.out.println("List is " + list);
        String[] arr = list.toArray(new String[0]);
        System.out.println("Array is " + Arrays.toString(arr));

Solution

  • You can try to use label. So basically the break in your case 3 only breaks outside switch statement but not outside the do while loop. You can add a statement before do as below:

    outerloop:
    do{
      switch(a){
      // rest of your logic
      case 3:
      break outerloop;
      }
    }
    while(true)
    

    where outerloop is a label. Please try this.