简体   繁体   English

java从数组中删除元素

[英]Deleting element from an array in java

I created a program where users enter a command which are : adding a number to the array or delete an element from the array or print the array.我创建了一个程序,用户可以在其中输入以下命令:向数组添加数字或从数组中删除元素或打印数组。 The array size is 10.数组大小为 10。

Here is the tester class,这是测试员课程,

   import java.util.Scanner;
   public class Assignment7 {

   public static void main (String [] args) {

    Scanner scan = new Scanner (System.in);
     final int MAX = 10;
      Numbers nums = new Numbers(MAX);

     char command;
     int value;

     System.out.println
       ("To add an element into the array, type a.");
      System.out.println
     ("To delete an element from the array, type d.");
     System.out.println
     ("To print the current contents of the array, type p.");
      System.out.println
      ("To exit this program, type x.\n");
      System.out.print
      ("Add (a), delete (d), print (p) or exit (x)?:");

      command = scan.nextLine().charAt(0);
       while (command != 'x') {
      if (command == 'a' || command == 'd') {
      System.out.print ("Enter a number: ");
       value = scan.nextInt();
       scan.nextLine();
      if (command == 'a')nums.add(value);
        else nums.delete(value);
        }
       else if (command == 'p') nums.print();
         else System.out.println ("Not a value input");

        System.out.print
        ("Add (a), delete (d), print (p) or exit (x)?: ");
        command = scan.nextLine().charAt(0);
         }
         System.out.println ("Program Complete");
      }
   }

And here is my other class,这是我的另一堂课,

       import java.util.*;

       public class Numbers{
    private int[] nums;
    private int size;

    public Numbers(int _size){
    this.nums = new int[_size];
    }

    public void add(int addnum){
    if (size == nums.length)
    {
        System.out.println("Array is full. The value " +addnum + " cannot                be added.");
    }
    else
    {
    nums[size] = addnum;
    size += 1;
    }

        }

      public void delete(int deleteNum){
    if(search(deleteNum) == -1)
    {
    System.out.println("The value " + deleteNum + " was not found and cannot be deleted.");
    }
    else {
        for (int i = nums[deleteNum]; i < nums.length -1; i++){
            nums[i]= nums[i+1];
        }
    }
     }

      public void print(){
    String output ="";
    for(int str: nums){
    output = output + " " + str;
        }
    System.out.println(output);

     }

     private int search(int x){
    int index = 0;
    while(index < size){
        if(nums[index] == x)
        return index;
        index++;
            }
        return -1;
        }
       }

Each time I run the program and input a number I want to delete it doesn't delete it.每次我运行程序并输入一个我想删除的数字时,它都不会删除它。 It deletes the number in the index.它删除索引中的数字。

For example, if the array inputs are 1,2,3,4,5,6,7,8,9,10 and I want to delete the number 1 it deletes the value that is in the index of 1 which would be the number 2 instead of the number 1.例如,如果数组输入是1,2,3,4,5,6,7,8,9,10并且我想删除数字 1,它会删除 1 的索引中的值,这将是数字 2 而不是数字 1。

I think that your "design" is not efficient.我认为你的“设计”效率不高。 Because in your small program your array size is changing during runtime.因为在您的小程序中,您的数组大小在运行时会发生变化。 Also your delete method is "weird".您的删除方法也很“奇怪”。

Why it's not efficient?为什么效率不高?

You're using static array that has fixed size -> so if you want to "correctly" delete item from it, you need to re-initialise new array with new (size - 1) 1 and this is such a spaghetti code operation.您正在使用具有固定大小的静态数组->因此,如果您想“正确”从中删除项目,则需要使用 new (size - 1) 1重新初始化新数组,这是一个意大利面条式代码操作。

And what is a suggestion?什么是建议?

What about to use dynamic array that can change its size dynamically when you'll remove or add new item to it?当您删除或添加新项目时,如何使用可以动态更改其大小的动态数组? It also offers directly methods like add and remove for manipulating with it.它还提供了直接的方法,例如添加和删除以对其进行操作。

1 You need to reinitialise static array (with new size - 1) again because if you'll "delete" for example 2. item from it it will be only assigned to zero so whole array will looks like: [ 1, 0, 3, 4, 5, 6, 7, 8, 9 ] and desired goal is [ 1, 3, 4, 5, 6, 7, 8, 9 ] 1您需要再次重新初始化静态数组(使用新大小 - 1),因为如果您将“删除”例如 2. 项目中的它只会被分配为零,因此整个数组将如下所示:[ 1, 0, 3 , 4, 5, 6, 7, 8, 9 ] 和期望的目标是 [ 1, 3, 4, 5, 6, 7, 8, 9 ]

tl;dr: use an ArrayList, or seperate your array operations into its own class. tl; dr:使用 ArrayList,或将您的数组操作分离到它自己的类中。

If you want to be able to add to and delete from a list, you most probably want to use an arraylist, which is implemented with an array "beneath the hood", but it supports a dynamic size.如果您希望能够在列表中添加和删除,您很可能希望使用一个数组列表,它是通过“底层”数组实现的,但它支持动态大小。 The most valid reason for you to use an array, and not some sort of collection is for learning purposes, in which case you should make your own "arraylist" so all code related to add/deleting/etc is contained within its own class.您使用数组而不是某种集合的最有效理由是出于学习目的,在这种情况下,您应该创建自己的“数组列表”,以便与添加/删除/等相关的所有代码都包含在其自己的类中。 Just know that your implementation is probably never gonna be as efficient and robust as ArrayList.只要知道您的实现可能永远不会像 ArrayList 那样高效和健壮。

When deleting elements you do not need to "resize" the array, only keep a seperate size variable which tells you which indeces are "valid".删除元素时,您不需要“调整”数组的大小,只需保留一个单独的大小变量,告诉您哪些索引是“有效的”。 When adding new elements you have to initialize a new array with a greater size, if you have exceeded the array's length, and copy over all the elements from the old one.添加新元素时,如果超出了数组的长度,则必须初始化一个更大的新数组,并复制旧元素的所有元素。

In your delete method, you should store the value you get from your search method.在您的删除方法中,您应该存储从搜索方法中获得的值。 Right now you are calling nums[deleteNum] which is using the number inputted as an index.现在您正在调用 nums[deleteNum],它使用输入的数字作为索引。 This is why you are having value 2 deletes.这就是为什么您要删除值 2 的原因。 you should do something like this:你应该做这样的事情:

public static void delete(int deleteNum){
   int index = search(deleteNum);
    if(index == -1)
    {
    System.out.println("The value " + deleteNum + " was not found and cannot be deleted.");
    }
    else {
        int size = nums.length;
        for (int i = index; i < size; i++){
            if(i < (size-1)
                nums[i]= nums[i+1];
            else
                nums[i] = 0; //set to some base case or zero
        }
    }
     }

You will not be able to "delete" the last value, but instead have to set it to some base case.您将无法“删除”最后一个值,而必须将其设置为某个基本情况。 If you want to truly delete i.如果你想真正删除 i. you should use another data structure, ie ArrayList你应该使用另一种数据结构,即 ArrayList

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM