我不确定如何实现这一点。
假设我有两个类Dog和Cat
public class Dog
{
private int a, b;
private double c;
//Constructors etc
}
public class Cat
{
private int x, y;
private char z;
//Constructors etc
}
我也给了一个字符串
“a,b,c / x,y,z”
该字符串可以是任何组合,即猫/狗,狗/猫,狗/狗等,每个部分的第三个值要么是双倍的,要么是字符
我拆分了String并制作了两个数组。 这就是我到目前为止所做的:
public void object ()
{
//My code to Split the line on "/" into 2 parts
//splits the part on "," to create two String arrays
//oneArray[] is [a,b,c] twoArray[] is [x,y,z]
oneArray[2] = ?? //Not sure how to create the right object that matches the data type
twoArray[2] = ??
}
当第三个值是不同的数据类型时,无论字符串组合如何创建两个对象?
答案 0 :(得分:1)
您可以尝试这样的事情:
List<Object> animalsList = new ArrayList<>(); // Will contains list of all animals
String input = "Cat/Dog, Dog/Cat ,Dog/Dog "; // Sample Input List
String [] inputEntries = input.split(","); // Separating based on comma
for(String inputEntry: inputEntries)
{
String [] animals = inputEntry.split("/");
for(String animal: animals)
{
objectList.add(animal.equalsIgnoreCase("Cat")?new Cat():new Dog());
/\
||
||
You can pass the values to constructor from here
}
}
答案 1 :(得分:0)
下面的代码以更面向对象的方式解决您的问题:
实用程序方法(检查第三个元素是否可解析为Double或默认为String):
private List<Animal> splitLine(String line)
{
List<Animal> objectList = new ArrayList<>();
String[] elements = line.split("/");
for (int i = 0; i < elements.length; i++)
{
try
{
Cat cat = new Cat(Integer.valueOf(elements[i].charAt(0)), Integer.valueOf(elements[i].charAt(1)), Double.valueOf(elements[i].charAt(
2)));
objectList.add(cat);
}
catch (NumberFormatException e)
{
Dog dog = new Dog(Integer.valueOf(elements[i].charAt(0)), Integer.valueOf(elements[i].charAt(1)), "" + elements[i].charAt(2));
objectList.add(dog);
}
}
return objectList;
}
通用界面:
interface Animal
{
}
班级犬:
class Dog implements Animal
{
private Integer a;
private Integer b;
private String c;
public Dog(Integer a, Integer b, String c)
{
super();
this.a = a;
this.b = b;
this.c = c;
}
}
Class Cat:
class Cat implements Animal
{
private Integer x;
private Integer y;
private Double c;
public Cat(Integer x, Integer y, Double c)
{
super();
this.x = x;
this.y = y;
this.c = c;
}
}