Java - get an Integer value from String or int - avoiding instanceof - java

Is there a single line implementation for the getInt method?
If not - can one implement it without using instanceof?
public class ParseInt {
public static void main(String[] args) {
Object intArr[] = { "131", 232, new Integer(333) };
for (Object intObj : intArr) {
System.out.println(getInt(intObj));
}
}
private static int getInt(Object obj) {
return // ???
}
}

Use Integer.valueOf(obj.toString)
private static int getInt(Object obj) {
return Integer.valueOf(obj.toString());
}
This will work for your object array

Try something like...
private static int getInt(Object obj) {
if (obj instanceof String) {
return Integer.parseInt((String) obj);
} else if(obj instanceof Integer){
return (Integer) obj;
} else{
return 0; // or else whatever you want
}
}

Related

How to print Array smart in java?

I want print single variable, array and maybe double array,
I use following code, add a type when I need it,
but ... as you see ... it works but not smart.
So, question is "Is there a smart way to print Arrays?"
import java.util.Arrays;
class Rec{
int val;
public String toString(){
return "" + val;
}
Rec(int val){this.val=val;}
}
public class Main
{
public static void main(String[] args) {
Rec r = new Rec(0);
Boolean[] ba = new Boolean[]{true, false, true, true};
Rec[] ra = new Rec[]{new Rec(1), new Rec(2), new Rec(3)};
int[][] iaa = new int[][]{{1,2,3}, {3,4,5}};
System.out.printf("r=%s ba=%s ra=%s iaa=%s \n", s(r), s(ba), s(ra), s(iaa));
}
static <T> String s(T n) {
if(n instanceof int[]){
return Arrays.toString((int[])n);
}else if(n instanceof int[][]){
return Arrays.deepToString((int[][])n);
}else if(n instanceof boolean[]){
return Arrays.toString((boolean[])n);
}else if(n instanceof boolean[][]){
return Arrays.deepToString((boolean[][])n);
}else if(n instanceof Boolean[]){
return Arrays.toString((Boolean[])n);
}else if(n instanceof Rec[]){
return Arrays.toString((Rec[])n);
//}else if(n instanceof T[]){ // error: illegal generic type for instanceof
// return Arrays.toString((T[])n);
}else{
return "" + n;
}
}
}
If you really want to customize your printing for variable arrays then why not do the following:
public static String s(Object s) {
return s.toString();
}
public static String s(Object[] s) {
return Arrays.toString(s);
}
public static String s(Object[][] s) {
return Arrays.deepToString(s);
}
// For each primitive type of your single or multi dimension
// declare the following for either single or multi dimensional
public static String s(int[][] s) {
return Arrays.deepToString(s);
}
public static String s(int[] s) {
return Arrays.toString(s);
}
But keep in mind you are basically repackaging what the API already does.

How to avoid this multiple if else condition in java

My code looks like
public void convertValues(String sourceValue,String targetValue) {
if (sourceValue.equals(targetValue)) {
//dosomething
} else if (sourceValue.equals(value1) && targetValue.equals(value2)) {
//dosomething
} else if (sourceValue.equals(value2) && targetValue.equals(value1)) {
//dosomething
}
}
like that I have some 40 condition, I know writing those if else condition is stupidity.
Is it good approach to use enums or hashmaps?
To speedup entering a spaghetti code, you probably need to prepare a helper class that would simplify adding the repeated lines.
If you don't like using else if, use return; (Caution: snobbish people are allergic to seeing return not at the end).
Use a helper class / method for checking values.
Example:
public class Main {
String value1 = "a";
String value2 = "b";
String value3 = "c";
String value4 = "d";
// use a nested private class where you could add all long
// and repetitive methods that need to be done
// with source and target
private class Helper {
private String src;
private String tgt;
Helper(String src, String tgt) {
this.src = src;
this.tgt = tgt;
}
public boolean eq(String val, String val1) {
return src.equals(val) && tgt.equals(val1);
}
// add other repetitive functions here
}
public void convertValues(String sourceValue, String targetValue) {
// use a simple name for the helper class.
Helper $ = new Helper(sourceValue, targetValue);
if (sourceValue.equals(targetValue)) {
// put your execution lines into a separate method.
// this way, it will become reusable and much easier to maintain
// call a method1
return;
}
if ($.eq(value1, value2)) {
// call a method2
return;
}
if ($.eq(value2, value1)) {
// call a method3
return;
}
if ($.eq(value1, value3)) {
// call a method4
return;
}
// ....
}
// public void method1()
// public void method2()
public static void main(String[] args) throws java.lang.Exception {
// Everything else
}
}
Using lambda expressions in Java 8, it can be implemented like:
Define Value class:
public class Value {
private final String value1;
private final String value2;
// Function to exetute
private final BiConsumer<String, String> f;
public Value(String value1, String value2, BiConsumer<String, String> f) {
super();
this.value1 = value1;
this.value2 = value2;
this.f = f;
}
public boolean execute(String src, String tgt) {
if(src.equals(value1) && tgt.equals(value2)) {
f.accept(src, tgt);
return true;
}
return false;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value1 == null) ? 0 : value1.hashCode());
result = prime * result + ((value2 == null) ? 0 : value2.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Value other = (Value) obj;
if (value1 == null) {
if (other.value1 != null)
return false;
} else if (!value1.equals(other.value1))
return false;
if (value2 == null) {
if (other.value2 != null)
return false;
} else if (!value2.equals(other.value2))
return false;
return true;
}
}
// Initialize values
Set<Value> values = new HashSet<>();
values.add(new Value("value1", "value2", (src, tgt) -> {/* do something here */}));
values.add(new Value("value2", "value1", (src, tgt) -> {/* do something here */}));
values.add(new Value("value4", "value5", (src, tgt) -> {/* do something here */}));
// Execute
if (sourceValue.equals(targetValue)) {
//dosomething
} else {
for(Value v:values) {
if(v.execute(src, tgt)) {
break;
}
}
}

jcombobox setSelectedItem

I have a created a combo box with three items. I am trying to set the selected item by index and value.
When I do setSelectedIndex () the code works well.
I am trying to set the selected item by value. So I try creating another object, with same value(variable name d), and do setSelectedItem but it fails. When I try printing out the selectedItem, it doesn't print 'C C'. It prints the previously selected item 'B B'
So how do set selectedItem by value? Do advice.
Thanks so much!
import javax.swing.JComboBox;
public class testt {
public static void main(String[] args) {
obj a = new obj("A A");
obj b = new obj("B B");
obj c = new obj("C C");
obj[] lst = { a, b, c };
JComboBox box = new JComboBox(lst);
box.setSelectedIndex(1);
System.out.println("value is:"+((obj) box.getSelectedItem()).toString());
obj d = new obj("C C");
box.setSelectedItem(d);
System.out.println(value is:"+((((obj) box.getSelectedItem()).toString());
}
}
class obj {
String value;
public obj(String value) {
this.value = value;
}
public String toString() {
return value;
}
}
Equals and Hashcode issue. The below should solve the problem.
class obj {
String value;
public obj(String value) {
this.value = value;
}
public String toString() {
return value;
}
#Override
public int hashCode() {
int hash = 5;
hash = 17 * hash + Objects.hashCode(this.value);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final obj other = (obj) obj;
if (!Objects.equals(this.value, other.value)) {
return false;
}
return true;
}

Check ArrayList for duplicates

Class:
public class Variant
{
private String variant;
private String quantity;
//getters and setters
}
ArrayList:
ArrayList<Variant> variantList = getVariantsList();
Now I want to check whether variantList contains a duplicate entry of variant or not? Please note that variant having two entries with different quantity are to be considered as duplicates.
You can simply ovveride your equals method in your Variant class and provide all the rules for equality in that method.
#Override
public boolean equals(Object obj) {
..
Then you can use contains method or just pass it to a Set, that eliminates all your duplicates.
If you want variant having two entries with different quantity also considered as dup, then you can add that condition in your equals.
Override equals(Object obj) method and try to compare the object on variant and quantity.
Try to loop thru the variantList and do check for duplicity using variantList.contains(variant).
There are two things you need to do:
Override the equals() in your Variant class(minimal code below):
Please note that the below code only checks for quantity and not the variant prop. Your IDE might help you to generate the equals() as well.
#Override
public boolean equals(Object object) {
boolean isEqual = (this == object);
if(object instanceof Variant){
Variant variant = (Variant) object;
isEqual = this.quantity.equals(variant.quantity);
}else{
isEqual = false;
}
return isEqual;
}
Check if the List contains the object - which will use the equals() to check if both are equal.
for (Variant variant : variantList) {
if (variantList.contains(variant)) {
//do logic if its present
}
}
Just check one object with other objects of list
Override equals method in Variant class
#Override
public boolean equals(Object obj) {
if (obj != null) {
if (obj instanceof Variant) {
Variant temp = (Variant) obj;
return this.quantity.equals(temp.quantity); //for different quantity
} else {
return false;
}
}
return false;
}
Then check :
for (int i = 0; i < variantList.size(); i++) {
for (int j = 0; j < variantList.size(); j++) {
if (i != j) {
if (iList.get(i).equals(iList.get(j))) {
//logic when duplicate
break;
}
}
}
}
Follow the below guidelines:
Your Class Variant must override the equals method, since you define a duplicate condition based on quality hence in the equals method check for quality attribute value i.e.
public class Variant {
private String variant;
private String quantity;
public Variant(String variant, String quantity) {
this.variant = variant;
this.quantity = quantity;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((quantity == null) ? 0 : quantity.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Variant other = (Variant) obj;
if (quantity == null) {
if (other.quantity != null)
return false;
} else if (!quantity.equals(other.quantity))
return false;
return true;
}
}
Create a method which basically checking whether your list contains the duplicate entries(Variant) or not and return true and false accordingly:
private static boolean isListContainsDuplicateEntries(
ArrayList variantList) {
final List setToReturn = new ArrayList();
for (Variant v : variantList) {
if (!setToReturn.contains(v)) {
setToReturn.add(v);
} else {
return true;
}
}
return false;
}
Now, test the functionality:
public static void main(String[] args) {
Variant variant1 = new Variant("1", "100");
Variant variant2 = new Variant("2", "200");
Variant variant3 = new Variant("3", "200");
ArrayList<Variant> variantList = new ArrayList<>();
variantList.add(variant1);
variantList.add(variant2);
variantList.add(variant3);
System.out.println(Variant.isListContainsDuplicateEntries(variantList));
Output: true
You can use contains():
if (variantList.contains(**<some other Variant object>**)){
...
}
You can simply override your equals method in your Variant and try like this
List<Varient> list =getVariantsList();
System.out.println("here list size"+list.size());
Set<Varient> set = new HashSet<Varient>(list);
System.out.println("here"+set.size());
Create a varient Object:
public class Varient {
private String variant;
private String quantity;
public String getVariant() {
return variant;
}
public void setVariant(String variant) {
this.variant = variant;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Varient)) return false;
Varient varient = (Varient) o;
if (!quantity.equals(varient.quantity)) return false;
if (!variant.equals(varient.variant)) return false;
return true;
}
#Override
public int hashCode() {
int result = variant.hashCode();
result = 31 * result + quantity.hashCode();
return result;
}
}
Here is your main Program;
public class Test {
public static void main (String [] args){
// getVariantsList() here your list
List<Varient> list =getVariantsList();
Set<Varient> set = new LinkedHashSet<Varient>(list);
}
}
public class Variant {
private String variant;
private String quantity;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((variant == null) ? 0 : variant.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Variant other = (Variant) obj;
if (variant == null) {
if (other.variant != null)
return false;
} else if (!variant.equals(other.variant))
return false;
return true;
}
public String getVariant() {
return variant;
}
public void setVariant(String variant) {
this.variant = variant;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public static void main(String[] args) {
// HashSet<Variant> set = new HashSet<>();
// LinkedHashSet<Variant> linkedSet = new LinkedHashSet<>(); // stores
// in input order
/*
* You can use treeset to store data in custom order, in this case
* lexicographically
*/
TreeSet<Variant> treeSet = new TreeSet<>(new VariantComparator());
}
}

How to identify an instance of multidimensional object in java?

Is there any alternative way to identify instance of multidimensional object without hardcode on it?
//source
import java.util.LinkedList;
import java.util.List;
public class Test {
public static <T> boolean isPrimitiveWrapper(T p_obj) throws Exception {
if (Number.class.isInstance(p_obj) || Number[].class.isInstance(p_obj)) {
return true;
} else if (Boolean.class.isInstance(p_obj) || Boolean[].class.isInstance(p_obj)) {
return true;
} else if (Character.class.isInstance(p_obj) || Character[].class.isInstance(p_obj)) {
return true;
}
return false;
}
public static void main(String[] args) throws Exception {
Integer[][][] a = {{{0}}, {{1}}, {{0}}};
println(isPrimitiveWrapper(a));
println(isPrimitiveWrapper(a[0]));
println(isPrimitiveWrapper(a[0][0]));
println(isPrimitiveWrapper(a[0][0][0]));
}
public static <T> void println(T p_t) {
System.out.println(p_t);
}
}
//Actual Result
false
false
true
true
//Expected Result
true
true
true
true
Based on the example above, we have no problem to deal with non-array & single dimension array object, but it is fail to identify multidimensional array object.
It is too ugly to hardcode the number of dimension.
There's no standard way to determine, if the class itself is wrapper for primitive type or not, so, you can do something like this:
private static final Set <Class <?>> primitiveWrappers;
static {
Set <Class <?>> tmp = new HashSet<>();
tmp.add (Integer.class);
tmp.add (Boolean.class);
tmp.add (Character.class);
tmp.add (Long.class);
tmp.add (Double.class);
tmp.add (Float.class);
// ... have I forgotten smth?
primitiveWrappers = Collections.unmodifiableSet(tmp);
}
private static boolean isPrimitiveWrapperOrArrayOf(Object o) {
if (o.getClass().isArray())
return isPrimitiveWrapperOrArrayOf(o.getClass().getComponentType());
else
return primitiveWrappers.contains(o.getClass());
}
When you run isPrimitiveWrapperOrArrayOf, the class is being checked if it's array, if it is, we'll check it's component type (for example, that would be Integer[] for Integer[][]) in the same function isPrimitiveWrapperOrArrayOf, so this way we'll come to just SomeClass, which will be checked if it's contained inside hardcoded primitiveWrappers
By the way, you may take a look at Commons Lang, ClassUtils.wrapperToPrimitive may solve your problem.
Try this approach. I guess that's what you want.
But this code looks like some sort of a hack anyway
(which is not necessarily bad).
private static boolean isPrimitiveWrapper(Object obj){
if (obj == null) {
return false;
} else {
String cls = obj.getClass().getCanonicalName();
return "java.lang.Integer".equals(cls) ||
cls.startsWith("java.lang.Integer[]");
}
}
Here is another hack. Both codes should work OK though.
private static boolean isPrimitiveWrapper(Object obj){
if (obj == null) {
return false;
} else {
String cls = obj.getClass().getName();
cls = cls.replaceAll(";", "");
return cls.matches("\\[*L?java\\.lang\\.Integer");
}
}
public class Test {
public static <T> boolean isPrimitiveWrapper(T p_obj) throws Exception {
return isPrimitiveWrapper(p_obj.getClass());
}
public static boolean isPrimitiveWrapper(Class p_obj) throws Exception {
if (Number.class.isAssignableFrom(p_obj)) {
return true;
} else if (Boolean.class.isAssignableFrom(p_obj)) {
return true;
} else if (Character.class.isAssignableFrom(p_obj)) {
return true;
} else if (p_obj.isArray()) {
//To handle multi dimension array
while (p_obj.isArray()) {
p_obj = p_obj.getComponentType();
}
return isPrimitiveWrapper(p_obj);
}
return false;
}
public static boolean isPrimitiveWrapper(boolean p_obj) {
return false;
}
public static boolean isPrimitiveWrapper(byte p_obj) {
return false;
}
public static boolean isPrimitiveWrapper(short p_obj) {
return false;
}
public static boolean isPrimitiveWrapper(float p_obj) {
return false;
}
public static boolean isPrimitiveWrapper(int p_obj) {
return false;
}
public static boolean isPrimitiveWrapper(long p_obj) {
return false;
}
public static boolean isPrimitiveWrapper(char p_obj) {
return false;
}
public static boolean isPrimitiveWrapper(double p_obj) {
return false;
}
public static void main(String[] args) throws Exception {
Integer[][][] a = {{{0}}, {{1}}, {{0}}};
int[][][] b = {{{0}}, {{1}}, {{0}}};
println(isPrimitiveWrapper(a));
println(isPrimitiveWrapper(a[0]));
println(isPrimitiveWrapper(a[0][0]));
println(isPrimitiveWrapper(a[0][0][0]));
println(isPrimitiveWrapper(b));
println(isPrimitiveWrapper(b[0]));
println(isPrimitiveWrapper(b[0][0]));
println(isPrimitiveWrapper(b[0][0][0]));
}
public static <T> void println(T p_t) {
System.out.println(p_t);
}
}

Categories

Resources