【问题标题】:How to delete some elements from an array?如何从数组中删除一些元素?
【发布时间】:2014-03-21 19:10:58
【问题描述】:

我有一个问题:程序可以根据给定的序列号删除衣服。
当基于给定的事物时,我不知道如何删除一些元素。关于案例 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);
                        }
    }

【问题讨论】:

标签: java arrays elements base


【解决方案1】:

我不建议使用数组 - 当您拥有集合的魔力时。从数组中删除元素需要“重新洗牌”整个数组以消除“间隙”或编写代码以便在访问之前检查数组中每个位置的内容。更不用说数组是固定大小的(必须扩展才能添加更多)。

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

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

附:该代码的优化非常糟糕 - 数组列表会大大加快速度(甚至是 HashMap)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    相关资源
    最近更新 更多