java如何从数组中删除一些元素?
我有一个问题:该程序可以根据给定的串行代码删除衣服
我不知道如何删除一些元素时,它基于一个给定的东西。关于案例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 楼答案
我不建议使用数组-当你拥有集合的魔力时。从数组中删除元素需要对整个数组进行“重新排列”,以消除“间隙”或编写代码,以便在访问之前检查数组中每个位置的内容。更不用说数组是固定大小的(必须扩展才能添加更多)
这里可以使用泛型类型ArrayList,它支持以下方法。拆下(T)和。加(T)
另外,这看起来像是一个家庭作业问题:)你可能有一本教科书或同学可以在课堂上回答这个问题
另外,代码优化得非常糟糕-数组列表会大大加快它的速度(甚至是哈希映射)