删除没有数组列表的方法

时间:2014-02-04 22:28:18

标签: java object

我需要在不使用阵列列表的情况下实现删除方法。我需要使用一组循环来完成它。这是我的删除方法和添加方法以及使用的任何其他重要变量。关于我的代码有什么问题的任何建议都会很棒。

EDITED:更改了对值的引用比较。似乎反复工作。     final int MAX_DEVICES = 5;

   // Array of devices
   private Device list[] = new Device[MAX_DEVICES];

   // Number of Devices currently in the list
   // "Valid" Devices are stored in cells 0 - (numDevices - 1)
   private int numDevices = 0;

   Scanner stdin;  // read from stdin

 private void Add()
   {
      String thisName;
      int numThisRead;
      float thisInitVal;

      thisName = stdin.next();
      numThisRead = stdin.nextInt();
      thisInitVal = stdin.nextFloat();

      if(numDevices > MAX_DEVICES)
         System.out.println("The List was full. " + thisName +
               " was not added to the list.");
      else
      {
         Device myDevice = new Device(thisName, numThisRead, thisInitVal);
         list[numDevices] = myDevice;
         numDevices ++;
         System.out.println(thisName + " device has been added to the list.");
      }
   }

   private void Delete() //ASK QUESTION
   {
      String thisDelete;
      thisDelete = stdin.next();
      for(int i = 0; i < MAX_DEVICES; ++i)
      {
         if(list[i].getName().equals(thisDelete)) //if you find the name
         {
            System.out.println(list[i].getName() + " was deleted from the "
                  + "list.");
            for(int j = i; j < numDevices - 1; j++)
               list[j] = list[j + 1];
            numDevices--;
            return;
         }
      }
      System.out.println(thisDelete + " not deleted. It is not in the list.");
   }

1 个答案:

答案 0 :(得分:1)

如果需要避免使用数据类型List,可以将对象放在数组中。然后,您可以将一个元素声明为比当前数组小的数组,并将除了要删除的元素之外的所有元素复制到新数组中。然后返回新数组。