这是我的代码,我必须附加一个字符串,以便我可以像 name,email,phoneNumber 那样输出,这是我想的两种方式
String matchedFields = "";
DuplicateApplicantPojo duplicateApplicantPojo = new DuplicateApplicantPojo();
if (applicant.getApplicantName().equals(detectionPojo.getName())) {
matchedFields = DuplicateSettingsConstants.LABEL_NAME;
}
if (applicant.getApplicantEmail1().equals(detectionPojo.getEmail1())) {
matchedFields = ", " + DuplicateSettingsConstants.LABEL_EMAIL;
}
if (applicant.getApplicantCellPhone().equals(detectionPojo.getCellPhone())) {
matchedFields = ", " + DuplicateSettingsConstants.LABEL_PHONE;
}
另一种方式是
String matchedFields[] = new String[3];
int i=0;
DuplicateApplicantPojo duplicateApplicantPojo = new DuplicateApplicantPojo();
if (applicant.getApplicantName().equals(detectionPojo.getName())) {
matchedFields[i] = DuplicateSettingsConstants.LABEL_NAME;
i++;
}
if (applicant.getApplicantEmail1().equals(detectionPojo.getEmail1())) {
matchedFields[i] = DuplicateSettingsConstants.LABEL_EMAIL;
i++;
}
if (applicant.getApplicantCellPhone().equals(detectionPojo.getCellPhone())) {
matchedFields[i] = DuplicateSettingsConstants.LABEL_PHONE;
}
String matched=matchedFields[0];
for(int j=1;j<matchedFields.length;j++)
{
matched=", "+matchedFields[i];
}
我更喜欢哪种方式?还是有其他办法我可以继续
答案 0 :(得分:1)
您的代码不需要做额外的事情。第一种方法就足够了。
第二种方法的时间复杂度和空间复杂度都会更大。 (虽然差异非常小)
答案 1 :(得分:0)
好吧,它们都不会起作用,因为你要覆盖之前的值,而不是只是在最后附加字符串。我会在if测试中执行它,因为那时你不会将内存分配给数组然后跟踪一个额外的int。如果你使用for循环方式使用字符串构建器会更好,请参阅:when to use StringBuilder in java
答案 2 :(得分:0)
第一个应该这样做,除了你可以使用StringBuilder附加“matchedFields”
StringBuilder matchedFields = new StringBuilder();
DuplicateApplicantPojo duplicateApplicantPojo = new DuplicateApplicantPojo();
if (applicant.getApplicantName().equals(detectionPojo.getName())) {
matchedFields.append(DuplicateSettingsConstants.LABEL_NAME);
}if (applicant.getApplicantEmail1().equals(detectionPojo.getEmail1())) {
matchedFields.append(" , ").append (DuplicateSettingsConstants.LABEL_EMAIL);
}
.
.
.
从API获取有关它的更多信息:http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
答案 3 :(得分:0)
我建议添加辅助方法:
private static String getMatched(String prefix, String s1, String s2, String label) {
String matchedFields = "";
if (s1.equals(s2)) {
matchedFields = prefix + label;
}
return matchedFields;
}
然后你可以写(+ DuplicateSettingsConstants的静态导入):
String matchedFields = "";
matchedFields += getMatched("", applicant.getApplicantName(), detectionPojo.getName(), LABEL_NAME);
matchedFields += getMatched(", ", applicant.getApplicantEmail1(), detectionPojo.getEmail1(), LABEL_EMAIL);
matchedFields += getMatched(", ", applicant.getApplicantCellPhone(), detectionPojo.getCellPhone(), LABEL_PHONE);