字符串数组到一个对象数组

时间:2022-09-25 08:02:49

Maybe there is a method that does this that I don't know about - I doubt it though - but I'm trying to convert an array of strings to an array of Objects. Here is the problem: I'm reading a file in from the command line. The file represents several classes of the following types each with their own data fields. Vehicle is the parent class of all who follow: Vehicle,Car,American Car, Foreign car, Truck, Bicycle.

也许有一种方法可以做到这一点,我不知道 - 我怀疑它 - 但我正在尝试将一个字符串数组转换为一个对象数组。这是问题:我正在从命令行读取文件。该文件表示以下类型的几个类,每个类都有自己的数据字段。车辆是所有人的父母类:车辆,汽车,美国汽车,外国汽车,卡车,自行车。

I have no problem reading the file into a string array. However I need to create objects of all these types and store them in an array of type Vehicle[]. For example a portion of the file looks like this:

我将文件读入字符串数组没有问题。但是我需要创建所有这些类型的对象并将它们存储在Vehicle []类型的数组中。例如,文件的一部分如下所示:

  • Vehicle
  • Kim Stanley Robinson
  • 金斯坦利罗宾逊

  • 2344 court drive
  • 法庭开车2344

  • (221)885-7777
  • *@overflow.com
  • American Car
  • John Bunyon
  • 1010 binary lane
  • 1010二进制车道

  • (221)885-55643
  • bgt.com
  • convertable
  • made in detroit
  • 在底特律制造

  • union plant

Where Class type is the first line followed by, Owner's Name, address, phone number, email address...Each type has fields particular to it. So a foreign car is not made in Detroit. Each of these fields appear on a separate line in the file. So what I've done is read the entire file into a string array. However, I need to find my types in the array of strings,create objects of those types, and store them in a Vehicle array. My main problem is that each data field is on a separate line. How should I approach this problem? This is java code by the way.

其中Class类型是第一行,所有者的姓名,地址,电话号码,电子邮件地址......每种类型都有特定的字段。所以外国汽车不是在底特律生产的。这些字段中的每一个都显示在文件的单独行中。所以我所做的就是将整个文件读入一个字符串数组。但是,我需要在字符串数组中找到我的类型,创建这些类型的对象,并将它们存储在Vehicle数组中。我的主要问题是每个数据字段都在一个单独的行上。我该如何处理这个问题?这是java代码的方式。

8 个解决方案

#1


2  

Initially reading the data into a String array is fine. Then you need to loop through that array, and based on the "first line" of each loop ("Vehicle", "American car" etc) you will know how many subsequent elements of the array belong to the same.

最初将数据读入String数组是很好的。然后你需要遍历那个数组,并根据每个循环的“第一行”(“车辆”,“美国汽车”等),你将知道该数组的后续元素有多少属于同一个。

Something like this (i'll let you fill in the blanks yourself):

像这样的东西(我会让你自己填空):

int i = 0;
ArrayList<vehicle> vehicles = new ArrayList();
while (i < data.length)
{
  if (data[i].equalsIgnoreCase("vehicle"))
  {
    Vehicle vehicle = new Vehicle();
    vehicle.setOwner(data[++i]);
    ...
    vehicles.add(vehicle);
  }
  else if (data[i].equalsIgnoreCase("american car"))
  {
    ...
  }
  i++;
}

#2


1  

question is unclear. Do you want to know how to parse the file and use the words on each line to create a object of it?

问题不清楚。您想知道如何解析文件并使用每行上的文字来创建它的对象吗?

pseudo:

Vehicle_ptr myVeh = null;
for each line in file
switch line
{
case vehicle: myVeh = new Vehicle();
case American Car : myVeh = new AmericanCar();
default:
if (line.startswithaninteger && (myVeh != NULL)) myVeh.address = line;
etcetc.
}

Tips: use typeidentifiers in the textfile.for example: car:americancar address:12345 bla etcetc

提示:在textfile中使用typeidentifiers。例如:car:americancar address:12345 bla etcetc

Or use a serializer

或者使用序列化器

#3


0  

You could read the file as you are doing just now but when you read a string that is a Class type create an instance of the correct Vehicle type. It would appear that you would then know that the next x lines of the file are properties of that particular type so you would read the properties and set them on your Vehicle instance. You then have your Vehicle instance to add to the Vehicle array.

您可以像刚才那样读取文件,但是当您读取类型的字符串时,请创建正确的Vehicle类型的实例。看来您会知道该文件的下一行是该特定类型的属性,因此您将读取属性并在Vehicle实例上设置它们。然后,将Vehicle实例添加到Vehicle阵列。

#4


0  

I would use a Factory pattern that creates Adapters. The factory would take the string (Vehicle, American Car) and the adapter would take the string array and current index. The adapter would be responsible to knowing how many indices to read and return the concrete object (or an interface).

我会使用一个工厂模式来创建适配器。工厂将采用字符串(Vehicle,American Car),适配器将采用字符串数组和当前索引。适配器将负责知道要读取多少索引并返回具体对象(或接口)。

IAdapter adapter = AdapterFactory.Create( "American Car" );
Object concreteObject = adapter.Popluate( stringArray, currentIndex );

Now, if you have control over how the data is stored, you might want to look into standard serialization, even JSON, to make processing easier.

现在,如果您可以控制数据的存储方式,您可能需要查看标准序列化,甚至是JSON,以便于处理。

#5


0  

It seems to me you need a factory pattern to build your set of vehicle types from the inputs. The factory can look after determining where one car specification starts and another one ends. It'll then determine the set of fields for a car, and determine the car type. It can then call the appropriate constructor, passing in all the related fields.

在我看来,您需要一个工厂模式来从输入中构建您的车辆类型集。工厂可以确定一个汽车规格的开始位置和另一个汽车规格的结束位置。然后它将确定汽车的字段集,并确定汽车类型。然后它可以调用适当的构造函数,传入所有相关字段。

This means that a constructor of (say) an American car specifies all the fields that it's interested in. A European car constructor would do the same. Each constructor can assert on what it's been given so you don't create any cars incorrectly.

这意味着(比如说)美国汽车的构造函数指定了它感兴趣的所有字段。欧洲汽车构造函数也会这样做。每个构造函数都可以断言它给出的内容,因此您不会错误地创建任何汽车。

The factory will look after parsing and separating the inputs, and determining what is to be built. Each type of car's constructor looks after info for that car only, and performs the appropriate asserts.

工厂将负责解析和分离输入,并确定要构建的内容。每种类型的汽车构造函数都只关注该汽车的信息,并执行相应的断言。

The factory will maintain the list of cars created, and return that list (of America/European/Japanese) upon completion.

工厂将保留已创建的汽车列表,并在完成后返回该列表(美国/欧洲/日本)。

In pseudo-code:

whilst(!done) {
   fields.add(fieldFromFile);

   if (carSpecificationCompleted) {
       type = getType(fields);
       if (type == 'American') {
          car = new AmericanCar(fields);
       }
       else if (type == 'European') {
          car = new EuropeanCar(fields);
       }
       cars.add(car);
       clearStoredFields();
   }
}

#6


0  

Do you have control of the file being passed in? If so, might I suggest formatting it using XML and then parsing it using JDOM? It would make your life easier in terms of parsing. For example, you could format all vehicle entries like this:

你能控制传入的文件吗?如果是这样,我可以建议使用XML格式化它,然后使用JDOM解析它吗?在解析方面,它会让您的生活更轻松。例如,您可以格式化所有车辆条目,如下所示:



    <node type="vehicle>
       <attributes location="detroit" color="red" />
    </node>

Or whatever format you come up with. The benefit of this is you can then read in only the vehicles (or whatever you want), or use XPath or some other technology to efficiently get the info you want/need and load it to the proper datatype.

或者你提出的任何格式。这样做的好处是您可以只读取车辆(或任何您想要的),或使用XPath或其他技术有效地获取您想要/需要的信息并将其加载到正确的数据类型。

Disregard this advice if you have no control over file formatting.

如果您无法控制文件格式,请忽略此建议。

#7


0  

When you have the choice, change your file format.

如果有选择,请更改文件格式。

You can serialize your object by using xstream. Then you only have to store the complete Java object without checking if some value is existing.

您可以使用xstream序列化对象。然后,您只需存储完整的Java对象,而无需检查是否存在某个值。

#8


0  

I'd use the Builder pattern here instead of Factory. No big difference but find it a bit easier when the parameters vary like it seems to do in his example.

我在这里使用Builder模式而不是Factory。没有太大的区别,但是当参数变化时,发现它会更容易,就像在他的例子中看起来那样。

#1


2  

Initially reading the data into a String array is fine. Then you need to loop through that array, and based on the "first line" of each loop ("Vehicle", "American car" etc) you will know how many subsequent elements of the array belong to the same.

最初将数据读入String数组是很好的。然后你需要遍历那个数组,并根据每个循环的“第一行”(“车辆”,“美国汽车”等),你将知道该数组的后续元素有多少属于同一个。

Something like this (i'll let you fill in the blanks yourself):

像这样的东西(我会让你自己填空):

int i = 0;
ArrayList<vehicle> vehicles = new ArrayList();
while (i < data.length)
{
  if (data[i].equalsIgnoreCase("vehicle"))
  {
    Vehicle vehicle = new Vehicle();
    vehicle.setOwner(data[++i]);
    ...
    vehicles.add(vehicle);
  }
  else if (data[i].equalsIgnoreCase("american car"))
  {
    ...
  }
  i++;
}

#2


1  

question is unclear. Do you want to know how to parse the file and use the words on each line to create a object of it?

问题不清楚。您想知道如何解析文件并使用每行上的文字来创建它的对象吗?

pseudo:

Vehicle_ptr myVeh = null;
for each line in file
switch line
{
case vehicle: myVeh = new Vehicle();
case American Car : myVeh = new AmericanCar();
default:
if (line.startswithaninteger && (myVeh != NULL)) myVeh.address = line;
etcetc.
}

Tips: use typeidentifiers in the textfile.for example: car:americancar address:12345 bla etcetc

提示:在textfile中使用typeidentifiers。例如:car:americancar address:12345 bla etcetc

Or use a serializer

或者使用序列化器

#3


0  

You could read the file as you are doing just now but when you read a string that is a Class type create an instance of the correct Vehicle type. It would appear that you would then know that the next x lines of the file are properties of that particular type so you would read the properties and set them on your Vehicle instance. You then have your Vehicle instance to add to the Vehicle array.

您可以像刚才那样读取文件,但是当您读取类型的字符串时,请创建正确的Vehicle类型的实例。看来您会知道该文件的下一行是该特定类型的属性,因此您将读取属性并在Vehicle实例上设置它们。然后,将Vehicle实例添加到Vehicle阵列。

#4


0  

I would use a Factory pattern that creates Adapters. The factory would take the string (Vehicle, American Car) and the adapter would take the string array and current index. The adapter would be responsible to knowing how many indices to read and return the concrete object (or an interface).

我会使用一个工厂模式来创建适配器。工厂将采用字符串(Vehicle,American Car),适配器将采用字符串数组和当前索引。适配器将负责知道要读取多少索引并返回具体对象(或接口)。

IAdapter adapter = AdapterFactory.Create( "American Car" );
Object concreteObject = adapter.Popluate( stringArray, currentIndex );

Now, if you have control over how the data is stored, you might want to look into standard serialization, even JSON, to make processing easier.

现在,如果您可以控制数据的存储方式,您可能需要查看标准序列化,甚至是JSON,以便于处理。

#5


0  

It seems to me you need a factory pattern to build your set of vehicle types from the inputs. The factory can look after determining where one car specification starts and another one ends. It'll then determine the set of fields for a car, and determine the car type. It can then call the appropriate constructor, passing in all the related fields.

在我看来,您需要一个工厂模式来从输入中构建您的车辆类型集。工厂可以确定一个汽车规格的开始位置和另一个汽车规格的结束位置。然后它将确定汽车的字段集,并确定汽车类型。然后它可以调用适当的构造函数,传入所有相关字段。

This means that a constructor of (say) an American car specifies all the fields that it's interested in. A European car constructor would do the same. Each constructor can assert on what it's been given so you don't create any cars incorrectly.

这意味着(比如说)美国汽车的构造函数指定了它感兴趣的所有字段。欧洲汽车构造函数也会这样做。每个构造函数都可以断言它给出的内容,因此您不会错误地创建任何汽车。

The factory will look after parsing and separating the inputs, and determining what is to be built. Each type of car's constructor looks after info for that car only, and performs the appropriate asserts.

工厂将负责解析和分离输入,并确定要构建的内容。每种类型的汽车构造函数都只关注该汽车的信息,并执行相应的断言。

The factory will maintain the list of cars created, and return that list (of America/European/Japanese) upon completion.

工厂将保留已创建的汽车列表,并在完成后返回该列表(美国/欧洲/日本)。

In pseudo-code:

whilst(!done) {
   fields.add(fieldFromFile);

   if (carSpecificationCompleted) {
       type = getType(fields);
       if (type == 'American') {
          car = new AmericanCar(fields);
       }
       else if (type == 'European') {
          car = new EuropeanCar(fields);
       }
       cars.add(car);
       clearStoredFields();
   }
}

#6


0  

Do you have control of the file being passed in? If so, might I suggest formatting it using XML and then parsing it using JDOM? It would make your life easier in terms of parsing. For example, you could format all vehicle entries like this:

你能控制传入的文件吗?如果是这样,我可以建议使用XML格式化它,然后使用JDOM解析它吗?在解析方面,它会让您的生活更轻松。例如,您可以格式化所有车辆条目,如下所示:



    <node type="vehicle>
       <attributes location="detroit" color="red" />
    </node>

Or whatever format you come up with. The benefit of this is you can then read in only the vehicles (or whatever you want), or use XPath or some other technology to efficiently get the info you want/need and load it to the proper datatype.

或者你提出的任何格式。这样做的好处是您可以只读取车辆(或任何您想要的),或使用XPath或其他技术有效地获取您想要/需要的信息并将其加载到正确的数据类型。

Disregard this advice if you have no control over file formatting.

如果您无法控制文件格式,请忽略此建议。

#7


0  

When you have the choice, change your file format.

如果有选择,请更改文件格式。

You can serialize your object by using xstream. Then you only have to store the complete Java object without checking if some value is existing.

您可以使用xstream序列化对象。然后,您只需存储完整的Java对象,而无需检查是否存在某个值。

#8


0  

I'd use the Builder pattern here instead of Factory. No big difference but find it a bit easier when the parameters vary like it seems to do in his example.

我在这里使用Builder模式而不是Factory。没有太大的区别,但是当参数变化时,发现它会更容易,就像在他的例子中看起来那样。