英文:
Comparing a String against values in a List<Integer>
问题
我有两个值,5和6,都是整数,它们是ArrayList的一部分。我还有另一个布尔方法,它有一个字符串输入,并且我必须比较该字符串的值,然后遍历该列表,查看该值是否与列表中的元素匹配。如果匹配,则应返回true,否则返回false。目标是查看我的值是否与列表中的某个值匹配。
该列表是常量类的一部分,而我的方法位于Validator类中。以下是我的代码:
Constants.java:
public static final List<Integer> TYPES = new ArrayList<Integer>(Arrays.asList(5, 6));
Validator.java:
public static boolean isPromoTypeFormatValid(String value) {
value = Util.getTrimmedValue(value);
int intValue = Integer.valueOf(value);
List<Integer> promoTypeList = scpduuConstants.PROMO_TYPES;
for (int i = 0; i < promoTypeList.size(); i++) {
if (promoTypeList.contains(intValue)) {
return true;
}
}
return false;
}
在比较字符串值与整数ArrayList值时,是否有更好的方法?当比较字符串值与ArrayList值(整数)时,是否会出现问题?我对此有点新,但正在努力找出最高效的方法。请为任何建议告诉我。
英文:
I have two values, 5 and 6, both of which are Integers, that are part of an ArrayList. I also have another boolean method that has a String input, and I am having to compare the value of that String and go through that list and see if that value matches an element in that list. If it does match, then I should return true, else false. The goal is to see if my value matches one of the values in the list.
The list is part of a constants class, and I have my method in a Validator class. Below is my code:
Constants.java:
public static final List<Integer> TYPES = new ArrayList<Integer> (Arrays.asList(5,6));
Validator.java:
public static boolean isPromoTypeFormatValid (String value) {
value = Util.getTrimmedValue(value);
int intValue = Integer.valueOf(value);
List <Integer> promoTypeList = scpduuConstants.PROMO_TYPES;
for(int i = 0; i < promoTypeList.size(); i++) {
if (promoTypeList.contains(intValue)) {
return true;
}
}
return false;
}
Is there a better way to do this, and would I get an issue when comparing the String value against the ArrayList value when it is an Integer? I'm a little new to this but trying to figure out the most efficient way possible. Please let me know for any suggestions.
答案1
得分: 1
也许这能稍微帮助一下:
public static final List<Integer> TYPES = new ArrayList<Integer>(Arrays.asList(5, 6));
public static void main(String[] args) {
final String value = "5";
checkValue(value);
}
public static boolean checkValue(String value) {
final var valueAsInt = Integer.parseInt(value.trim());
return TYPES.contains(valueAsInt);
}
英文:
Maybe this helps a bit:
public static final List<Integer> TYPES = new ArrayList<Integer>(Arrays.asList(5, 6));
public static void main(String[] args) {
final String value = "5";
checkValue(value);
}
public static boolean checkValue(String value) {
final var valueAsInt = Integer.parseInt(value.trim());
return TYPES.contains(valueAsInt);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论