我从 java 开始,我需要为我的第一个程序创建一个方法。
我要做的是:我一个接一个地创建字符串,并将它们保存在 String[] 数组中。这些字符串具有以下结构:
String = word1 word2 word3 code;
然后,当我需要时,我可以列出它们,在控制台上显示整个数组。而且,如果我愿意,我可以从数组中删除一个特定字符串。
为了实现这一点,我使用分配给每个数组的代码。每次我向数组中添加一个字符串时都会生成此代码,因此此代码与该字符串在数组中的位置相匹配。
当我想删除一个字符串时,我必须将字符串的代码传递给该方法。在这种情况下,代码与字符串的位置相同,因此当我传递代码时,实际上我传递的是位置。
第一次删除字符串时,这是有效的,但第二次因此失败。假设我们有:
String0 = word1 word2 word3 0
String1 = word4 word5 word6 1
String2 = word7 word8 word9 2
如果我删除 String1,现在数组的大小将调整为 2 个字符串(0 和 1),因此当我添加新字符串时,它会将代码 2 重新调整为这个新字符串,因此我将拥有:
String0 = word1 word2 word3 0
String2 = word7 word8 word9 2
String3 = word10 word11 word12 2
这一切都是因为将代码分配给字符串时,我使用了字符串在数组中的位置。 那么,以正确的方式实现此功能的最佳方式是什么?
这是我的代码:
我在 main 中以这种方式向数组添加一个字符串:
musicList.add(new Music(title, autor, format, code));
我以这种方式在控制台上列出数组:
System.out.println(musicList.toString());
我这样删除它:
musicList.delete(code);
方法 add()、toString() 和 delete() 是我在其他类中以这种方式定义的自定义方法:
public void add(Music m){
musicList[pos_counter] = m;
pos_counter++;
}
public void delete(int code){
Music[] tempMusic = new Music[musicList.length];
int index_1 = 0;
for (int i=0; i<musicList.length; i++){
if(i != code){
tempMusic[index_1] = musicList[i];
index_1++;
}
}
int index_2 = 0;
for (int i=0; i<tempMusic.length; i++){
musicList[index_2] = tempMusic[i];
index_2++;
}
pos_counter--;
}
toString() 方法只是以字符串方式显示实例。
Music[] 实例仅调用其他类,其中定义了带有音乐列表元素的构造函数(这些元素是标题、作者、格式或类型和代码):
public Music(String title, String autor, String type, int code){
this.setTitle(title);
this.setAutor(autor);
this.setType(type);
this.setCode(code);
}
最佳答案
首先,我建议使用ArrayList。但是我在您之前的问题中看到您不想使用它。所以,如果你想使用数组,那么你的代码就有问题。当您从数组中删除某些内容时,您需要更改数组中要删除的项目之后的所有项目的代码,否则代码将与位置不匹配。
编辑:要使用 ArrayList 执行此操作,您可以使用以下命令创建它:
ArrayList<Music> musicList = new ArrayList<Music>();
要添加和删除项目,只需:
musicList.add(new Music("string", "string", "string", musicList.size()));
// If you have the Music instance you want to remove, you can pass it as an argument
musicList.remove(musicItem);
// And if you only have the position, then
musicList.remove(position);
如果您使用 ArrayList,则不需要存储 Music 对象中的位置,但如果出于某种原因需要,则只需使用我编写的 size 方法作为 add 函数的最后一个参数。
编辑 2:要为添加到列表中的每个项目获取新代码,您可以尝试以下操作:
int max = 0;
for (Music item : musicList) {
if (item.getCode() > max) {
max = item.getCode();
}
}
int newCode = max++;
编辑3:在你解释完所有内容之后,我猜你真正想要的是一张 map 。使用 Map,您可以使用键存储项目,并使用该键检索值。您的情况的关键是音乐项目的代码。它看起来像这样:
Map<Integer, Music> musicMap = new HashMap<Integer, Music>();
// To put a new item in the Map
int max = 0;
for (Integer mapCode : musicMap.keySet()) {
if (mapCode > max) {
max = mapCode;
}
}
int newCode = max++;
musicItem.setCode(newCode);
musicMap.put(newCode, musicItem);
// To remove an item by its value
musicMap.remove(code);
您可以找到有关 map 界面的更多信息here .
最后编辑:要迭代 map 并将其输出打印到控制台,您只需执行以下操作:
for (Music item : musicMap.values()) {
System.out.println(item);
}
关于java - 使用定义的代码从数组中获取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20348955/