Java FindAndDelete方法中数组的全局索引在数组实例的不同类singenton中
我有一个带有singlton方法的类,包含所有DVD的数组Java FindAndDelete方法中数组的全局索引在数组实例的不同类singenton中,java,arrays,Java,Arrays,我有一个带有singlton方法的类,包含所有DVD的数组 public class DvdCon { private static ArrayList<Dvd> dvds; private static DvdCon instance; private static int i = 0; public DvdCon() { dvds = new ArrayList<Dvd>(); } publi
public class DvdCon
{
private static ArrayList<Dvd> dvds;
private static DvdCon instance;
private static int i = 0;
public DvdCon()
{
dvds = new ArrayList<Dvd>();
}
public static DvdCon getInstance()
{
if(instance == null)
{
instance = new DvdCon();
}
return instance;
}
public void addDvd(Dvd d)
{
dvds.add(d);
}
public void deleteDvd(Dvd d)
{
dvds.remove(d);
}
public Dvd findDvd(String title)
{
int i = 0;
boolean found = false;
while (!found && i<=dvds.size()){
if (title.equals (dvds.get(i).getTitle())){
found = true;
}
else {
i++;
}
if (found){
return dvds.get(i);
}
}
return null;
}
}
现在在findanddeledvd
方法中,我想使用I
索引,因为它是原始数组的单例实例。所以我不想要一个新的数组列表,我想要它查看实际的列表
但是当我尝试创建一个全局字段时,原始类的构造函数停止工作,因为int
。。。我该怎么做
实际问题再次出现:希望创建一个数组实例,以便只存在一个数组,当我查看
findAndDeleteDvd
中的索引时,我会找到列表中内容的实际全局结果,而不是一个新的数组实例。我不确定是否获得了程序的确切工作方式,但这里有一个建议:
仅供参考:在DvdCon
中,字段不需要是静态的
在您的findAndDeleteDvd()
中,您可能需要进行一些更改。您在上面发布的代码没有多大意义:)
如果按标题搜索,则需要将标题传递给方法
public void findAndDeleteDvd(String title) { // pass the title to the method
Dvd foundDvd = dCon.findDvd(title); // findDvd by title and save a local reference (no need for it to be global
deleteDvd(foundDvd); // delete the dvd (by its reference)
}
到目前为止还不错。另一个建议是帮助您使用搜索算法按dvd标题查找dvd:
在DvdCon中:
public Dvd findDvd(String title) {
for (Dvd dvd : dvds) { // loops through the whole list of dvds
if (dvd.getTitle().equalsIgnoreCase(title)) { // compares the dvd's title with the parameter title
return dvd; // if equal, return dvd
}
}
return null;
}
这样,您只需要标题
,而不需要索引。处理索引是一种直接的方法,但您可能会遇到更多的问题。例如,您不能始终确保列表中元素的顺序始终相同(例如,如果删除元素会发生什么情况)。如果有一天您决定使用HashMap而不是ArrayList,会发生什么。。。等等
因此:将标题传递给搜索方法,然后不按索引搜索标题。
嗯,我希望它在某种程度上有所帮助:)
public Dvd findDvd(String title) {
for (Dvd dvd : dvds) { // loops through the whole list of dvds
if (dvd.getTitle().equalsIgnoreCase(title)) { // compares the dvd's title with the parameter title
return dvd; // if equal, return dvd
}
}
return null;
}