[英]How can I return int and string attributes in a single Java method?
我想从BaseballPlayer
类返回所有属性的值。 需要执行此操作的方法必须是公共字符串getBaseballPlayer(int i)
方法(因为我需要在getBaseballPlayers()
引用此方法以将所有值作为字符串getBaseballPlayers()
返回)我在执行此操作时遇到了麻烦,因为所有属性具有不同的数据类型( int
、 String
、 Height
)。
我试过这样做:
public String getBaseballPlayer(int i){
ArrayList <String> bArray = new ArrayList <String>();
bArray.add(getHometown());
bArray.add(getState());
bArray.add(getHighSchool());
bArray.add(getPosition());
但是,它仅适用于字符串方法,并不一定返回实际值,而是返回每个字符串属性的 get 方法。
public class BaseballPlayer extends Player implements Table {
private int num;
private String pos;
public BaseballPlayer( int a, String b, String c, int d,
String e, String f, String g, Height h){
super(a,ft,in,c,d,e,f,ht);
num = a;
pos = b;
}
public BaseballPlayer(){}
//Returns the value of a specific attribute. The input parameter start
with 0 for the first attribute, then 1 for the second attribute and so
on.
//you can use getBaseballPlayer(int i) in getBaseballPlayers( ) with a for
loop getting each getBaseballPlayer(int i).
public String getBaseballPlayer(int i){
ArrayList <String> bArray = new ArrayList <String>();
bArray.add(getHometown());
bArray.add(getState());
bArray.add(getHighSchool());
bArray.add(getPosition());
return (bArray);
}
//Returns the value of all attributes as an ArrayList of Strings.
public ArrayList <String> getBaseballPlayers(){
}
我只是在寻找返回每个属性值的最简单方法,然后使用该方法将每个值作为另一个方法中的字符串数组列表返回。
将整个对象作为一个字符串返回不是一个好习惯。 除非,否则,您被迫这样做,不要尝试这样做。
好吧,如果您的要求无法更改,并且您希望 Baseball 对象中的所有内容都在一个字符串中,您可以使用“:”等分隔符连接所有参数。
例如:
public String getBaseballPlayer(int i){
return getHometown() + ":" + getState() + ":" +getHighSchool() + ":" + getPosition();
}
在调用端,您可以使用 String 的“split()”方法从此字符串中获取各个值。
你想做的,如果你想做得完美,就是Gson的存在。 它建立在简单的 JSON 之上,可以将任意类、数据结构和其他类型编码为 JSON,这样您就可以轻松地从 JSON 表示中重建这些对象。 考虑到它的实际功能有多强大,它很容易使用。
如果您不需要对 JSON 本身无法处理的类型进行编码,那么使用常规 JSON 会更容易。 在您的情况下,这似乎已经足够了。 JSON 的伟大之处在于它是一个标准。 您不必选择编码方案,并且您已经拥有用您能想到的任何语言编写的库,可以读取您的字符串化数据。
这是一个大致遵循您的代码正在执行的操作的示例:
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
public class BaseballPlayer {
private String name;
private String hometown;
private String state;
private int age;
private double height;
private String position;
static ObjectMapper mapper = new ObjectMapper();
public BaseballPlayer( String name, String hometown, String state, int age, double height, String position) {
this.name = name;
this.hometown = hometown;
this.state = state;
this.age = age;
this.height = height;
this.position = position;
}
public void setName(String name) {
this.name = name;
}
public void setHometown(String hometown) {
this.hometown = hometown;
}
public void setState(String state) {
this.state = state;
}
public void setAge(int age) {
this.age = age;
}
public void setHeight(float height) {
this.height = height;
}
public void setPosition(String position) {
this.position = position;
}
public String toString() {
return String.format("Name: %s from %s, %s (height: %.1f)", name, hometown, state, height);
}
public BaseballPlayer(){}
// Turn a BaseballPlayer object into a String
public String getAsJSON() {
Map<String, Object> info = new HashMap<>();
info.put("name", name);
info.put("hometown", hometown);
info.put("state", state);
info.put("age", age);
info.put("height", height);
info.put("position", position);
try {
return mapper.writeValueAsString(info);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Here's the method you ask for. I don't know what 'i' is supposed
// to do, since we're in the class for a single baseball player. You
// could create a class that contains a list of baseball players, but
// why not just use a List by itself, as I've done.
public String getBaseballPlayer(int i) {
return getAsJSON();
}
// Turn a list of BaseballPlayer objects into a list of Strings
public static List<String> playersToStrings(List<BaseballPlayer> players) {
List<String> r = new ArrayList<>();
for (BaseballPlayer player : players) {
r.add(player.getAsJSON());
}
return r;
}
// Turn a list of Strings into a list of BaseballPlayer objects
public static List<BaseballPlayer> stringsToPlayers(List<String> playerStrings) {
List<BaseballPlayer> r = new ArrayList<>();
for (String playerString : playerStrings) {
try {
BaseballPlayer player = mapper.readValue(playerString, BaseballPlayer.class);
r.add(player);
} catch (IOException e) {
e.printStackTrace();
}
}
return r;
}
public static void main(String... args) {
// Create a list of BaseballPlayer objects and print them
List<BaseballPlayer> players = new ArrayList<>();
players.add(new BaseballPlayer("Joe", "Boston", "MA", 25, 6.1, "First Base"));
players.add(new BaseballPlayer("Sam", "San Francisco", "CA", 28, 5.8, "Pitcher"));
players.add(new BaseballPlayer("Kelly", "Chicago", "IL", 32, 6.4, "Catcher"));
System.out.println(players);
// Convert the list to a list of Strings and print the list
List<String> playerStrings = playersToStrings(players);
System.out.println(playerStrings);
// Convert the Strings back into BaseballPlayer objects and print them
players = stringsToPlayers(playerStrings);
System.out.println(players);
}
}
这是结果输出:
[Name: Joe from Boston, MA (height: 6.1), Name: Sam from San Francisco, CA (height: 5.8), Name: Kelly from Chicago, IL (height: 6.4)]
[{"hometown":"Boston","name":"Joe","state":"MA","position":"First Base","age":25,"height":6.1}, {"hometown":"San Francisco","name":"Sam","state":"CA","position":"Pitcher","age":28,"height":5.8}, {"hometown":"Chicago","name":"Kelly","state":"IL","position":"Catcher","age":32,"height":6.4}]
[Name: Joe from Boston, MA (height: 6.1), Name: Sam from San Francisco, CA (height: 5.8), Name: Kelly from Chicago, IL (height: 6.4)]
在这里,每个玩家都被单独转换为 JSON。 再多几行代码,您就可以将 Baseball Player 对象数组转换为单个 String。
如果这个仅 JSON 的解决方案对您来说还不够好,请查看 Gson。 它可以保留所有 Java 类型。 只需要更多的设置来描述您的每个对象应该如何转换为 JSON 并返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.