如何从数组中删除一些元素?

时间:2014-03-21 19:10:59

标签: java arrays elements base

我有一个问题:程序可以根据给定的序列码删除衣服 基于给定的东西,我不知道如何删除一些元素。在案例3中,请帮助我。

import javax.swing.*;
public class piashop
{
public static void main (String args[])
    {
      Piafashion piatest[] = new Piafashion [370];
        JOptionPane.showMessageDialog (null, "Welcome to Pia Fashion Shop");
        int no_of_clothing = 0;
        int choice = 0;
        boolean found;
        String piatargetcode, piatargetcode1;
            do
            {
                choice = Integer.parseInt(JOptionPane.showInputDialog (null, "1. Add Product  2. Report  3. Delete"));
                switch(choice)
            {
                case 1:
                    String piascode = JOptionPane.showInputDialog (null, "Enter Brand ID");
                    String piapp = JOptionPane.showInputDialog (null, "Enter Purpose");
                    String piab = JOptionPane.showInputDialog (null, "Enter Brand");
                    String piac = JOptionPane.showInputDialog (null, "Enter Colour");
                    String pias = JOptionPane.showInputDialog (null, "Enter Size");
                    double piapr = Double.parseDouble(JOptionPane.showInputDialog (null, "Enter Price"));
                    piatest [no_of_clothing] = new Piafashion (piascode, piapp, piab, piac, pias, piapr);
                        no_of_clothing++;
                        break;
                //case 1 for adding elements array into database    

                case 2:
                    String piareport ="";
                    for (int x=0; x < no_of_clothing; x++)
                    piareport = piareport + "\nBrand ID is "+piatest[x].piaserial_code + "\nPurpose is " +piatest[x].piapurpose + "\nBrand is " +piatest[x].piabrand + "\nColour is " + piatest[x].piacolour + "\nSize is " + piatest[x].piasize + "\nPrice is " + piatest[x].piaprice +"\n";

                    JOptionPane.showMessageDialog(null, piareport);

                    break;

                //case 2 for displaying the product info                                            

                case 3:
                    }
                        }while(choice!=4);
                        }
    }

1 个答案:

答案 0 :(得分:1)

我不建议使用数组 - 当你拥有收藏的魔力时。从数组中删除元素需要重新排列&#39;整个阵列消除了“差距”。或者编写代码,以便在访问之前检查数组中每个位置的内容。更不用说数组是固定大小的(必须扩展才能添加更多)。

您可以在此处使用泛型类型ArrayList,它支持.remove(T)和.add(T)等方法。

另外这看起来像是一个家庭作业问题:)你可能有一本教科书或同学可以在课堂上回答这个问题。

P.S。该代码非常非常优化 - 数组列表会大大加快它(甚至是HashMap)