简体   繁体   English

Java如何创建一个接受两个列表类型的方法,而不是同时

[英]Java How to make a method that accepts two list types, not at the same time

I have this piece of code 我有这段代码

public void write(LinkedList<Drug> list, String file) {
    try (FileOutputStream fs = new FileOutputStream(System.getProperty("user.dir") + "\\res\\" + file + ".dat"); ObjectOutputStream os = new ObjectOutputStream(fs)) {
        System.out.println("Writing File...");
        os.writeObject(list);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

what I want is to use the same method to write a file of a different object for example 我想要的是使用相同的方法来编写不同对象的文件

LinkedList<String> temp = new LinkedList<>();
temp.add("Something");
temp.add("Something else");
write(temp, "stringlist");

and I don't want to just make a second method which will be 我不想只做第二种方法

public void writeSomething(LinkedList<String> list, String file) {
    try (FileOutputStream fs = new FileOutputStream(System.getProperty("user.dir") + "\\res\\" + file + ".dat"); ObjectOutputStream os = new ObjectOutputStream(fs)) {
        System.out.println("Writing File...");
        os.writeObject(list);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

如果您的方法没有使用列表中存储的对象类型,那么您可以将方法声明如下:

public void writeSomething(LinkedList<?> list, String file)

To answer your question literally as stated - to allow the method to accept exactly 2 list types - have two methods which call a private generic method: 要按字面意思回答你的问题 - 允许方法正好接受2个列表类型 - 有两个方法调用私有泛型方法:

public void writeDrugs(LinkedList<Drug> list, String file) {
  writeGeneric(list, file);
}

public void writeStrings(LinkedList<String> list, String file) {
  writeGeneric(list, file);
}

private void writeGeneric(LinkedList<?> list, String file) {
  // Implementation here.
}

Note that your two public methods would need to be named differently, as otherwise they would have the same erasure. 请注意,您的两个公共方法需要以不同的方式命名,否则它们将具有相同的擦除。

Of course, if you don't care about it being just these two types, you can simply make the writeGeneric (or whatever your want to call it) method public . 当然,如果你不关心它只是这两种类型,你可以简单地将writeGeneric (或任何你想要调用它)的方法public

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM