private void populateArrayOfObjects(Object[] params, Employee e){
params[0] = e.getName();
params[1] = e.getEmpId();
params[2] = e.getDesignation();
}
Is there any other way we can populate above array?
You can do it like this ;
params = Arrays.asList(e.getName(), e.getEmpId(),e.getDesignation()).toArray();
Create a list as Array.asList().And convert to array with toArray(). So you dont need to send to method. Just do with simple one line.
Related
How to pass multiple values in objType field to a method parameter
Currently i'm storing single row in objType field and passing that as an input to an oracle sp, now i need to store and pass multiple rows in objType. How to achieve that?
I've tried creating objType like multidimensional one:
Object[] objType = new Object[3][3],
it doesn't help.
Please see my sample code below and help.
Object[] objType = new Object[3];
objType[0] = new Integer(lineNo);
objType[1] = new String(itemCode);
objType[2] = new Integer(ORDER_QTY));
structs[index]=conn.createStruct("XXHDB_REC", objType);
Array reportsArray = ((OracleConnection)
conn).createOracleArray("XXHDB_TBL_TYPE", structs);
//Input to oracle package
oracleCallableStmt.setArray(4, reportsArray);
I need to store 'n' of rows with fixed 3 columns. [n][3].
Stored Proc Definition:
create_booking(p_reservation_id => p_reservation_id,
p_Hybris_Cust_nbr => p_Hybris_Cust_nbr,
p_cust_nbr => p_cust_order_no,
p_group => j.GROUP_ID,
p_order_lines => v_rec) --> this is the input field
Your example code Object[] objType = new Object[3][3] does not work as objType has the wrong type, it should be Object[][] objType = new Object[n][3]. However I strongly recommend to not use Object as type if you know the values you want to store, instead you could use some sort of container for them like:
class Container {
private Integer lineNo;
private String itemCode;
private Integer ORDER_QTY;
// rest omitted
}
And then use this as your type your array or whatever you want to use. Container[] objType = new Container[n];.
I am trying to build a string to pass it as an SQL query within the IN statement.
ArrayList<Object[]> arrayList = new ArrayList<Object[]>();
List<String> strings = new ArrayList<>(arrayList .size());
for (Object object : arrayList ) {
strings.add(Objects.toString(object, null));
}
System.out.println("askldnlkasdn"+strings);
This still prints out the memory locations instead of the actual string
askldnlkasdn[[Ljava.lang.Object;#7bb11784, [Ljava.lang.Object;#33a10788, [Ljava.lang.Object;#7006c658, [Ljava.lang.Object;#34033bd0, [Ljava.lang.Object;#47fd17e3, [Ljava.lang.Object;#7cdbc5d3, [Ljava.lang.Object;#3aa9e816, [Ljava.lang.Object;#17d99928, [Ljava.lang.Object;#3834d63f, [Ljava.lang.Object;#1ae369b7]
I have also tried out
using StringBuilder and StringUtils. But things dont seem to work.
Any inputs as to where the problem is?
you should override method toString in your objects
You can use an SQL specific java Array.
try (PreparedStatement stmt = connection.prepareStatement("... IN (?) ...")) {
Object[] elements = ...
stmt.setArray(1, connection.createArray("TEXT", elements));
stmt.executeUpdate();
}
The problem you have is that you are implicitly using the toString() method of the Object elements inside your ArrayList. By default, that method returns the class and address of the Object. You should override the toString() method in every class you will use inside the list so it returns what you want it to.
This is new code that may help,
// Data of Array of Object for test the Code
Object[] a = new Object[1];
a[0] = "Hello";
Object[] b = new Object[1];
b[0] = "Friend";
Object[] c = new Object[1];
c[0] = "This is";
Object[] d = new Object[1];
d[0] = "Just Test";
// The Array List of objects and the data entry
ArrayList<Object[]> arrayList = new ArrayList<Object[]>();
arrayList.add(a);
arrayList.add(b);
arrayList.add(c);
arrayList.add(d);
// New List of strings
List<String> strings = new ArrayList<>(arrayList .size());
// The Process of adding the data from array list of objects to the strings
for(int i = 0; i < arrayList.size(); i++){
strings.add((String) arrayList.get(i)[0]);
}
// Just for print the data to console
for(int i = 0 ; i < strings.size(); i++){
System.out.println(strings.get(i));
}
System.out.println("askldnlkasdn "+strings.get(0));
I hope that solve the problem, if not please inform me, you can use it for more than one dimensional array.
You can just save it as String , like this code
ArrayList<String> arrayList = new ArrayList<>();
List<String> strings = new ArrayList<>(arrayList .size());
for (Object object : arrayList ) {
strings.add(Objects.toString(object, null));
}
System.out.println("askldnlkasdn"+strings);
Or you want it Object for specific purpose?
First of all, I have created the object Sample, which looks like this:
public class Sample extends Model implements Comparable<Sample>{
public String content;
public Sample(String content) {
this.content = content;
}
}
Then, I create a List of Sample elements. After all that, what I'd like is to be able to create a simple String array in order to store this string content elements into a simple array to render it. My idea is to do something like:
String[] array = ...;
render(array);
With each component of this string being the content field of each Sample element. By doing that, I could "transfer" this array to operate with it later. How could I do that?
Using Java 8:
List<Sample> sampleList = ...;
String[] array = sampleList.stream()
.map(Sample::getContent)
.toArray(size -> new String[size]);
Using Java 7 or prior:
List<Sample> sampleList = ...;
String[] array = new String[sampleList.size()];
int i = 0;
for (Sample sample : sampleList) {
array[i++] = sample.getContent();
}
Use toArray() method forconverting Array to arraylist.
// create an empty array list with an initial capacity
ArrayList<Strng> arrlist = new ArrayList<String>();
// use add() method to add values in the list
arrlist.add("Anil");
arrlist.add("Vinod");
arrlist.add("Jaya");
arrlist.add("Arun");
// toArray copies content into other array
String list2[] = new String[arrlist.size()];
list2 = arrlist.toArray(list2);
Just a suggestion , if all you need is to create an array of contents , why not create a List from the Sample object and then invoke .toArray(). Did I miss something here ?
I have an ArrayList, Whom i convert to String like
ArrayList str = (ArrayList) retrieveList.get(1);
...
makeCookie("userCredentialsCookie", str.toString(), httpServletResponce);
....
private void makeCookie(String name, String value, HttpServletResponse response) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
response.addCookie(cookie);
} //end of makeCookie()
Now when i retrieve cookie value, i get String, but i again want to convert it into ArrayList like
private void addCookieValueToSession(HttpSession session, Cookie cookie, String attributeName) {
if (attributeName.equalsIgnoreCase("getusercredentials")) {
String value = cookie.getValue();
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
return;
}
String value = cookie.getValue();
session.setAttribute(attributeName, value);
} //end of addCookieValueToSession
How can i again convert it to ArrayList?
Thank you.
someList.toString() is not a proper way of serializing your data and will get you into trouble.
Since you need to store it as a String in a cookie, use JSON or XML. google-gson might be a good lib for you:
ArrayList str = (ArrayList) retrieveList.get(1);
String content = new Gson().toJson(str);
makeCookie("userCredentialsCookie", content, httpServletResponce);
//...
ArrayList userCredntialsList = new Gson().fromJson(cookie.getValue(), ArrayList.class);
As long as it's an ArrayList of String objects you should be able to write a small method which can parse the single String to re-create the list. The toString of an ArrayList will look something like this:
"[foo, bar, baz]"
So if that String is in the variable value, you could do something like this:
String debracketed = value.replace("[", "").replace("]", ""); // now be "foo, bar, baz"
String trimmed = debracketed.replaceAll("\\s+", ""); // now is "foo,bar,baz"
ArrayList<String> list = new ArrayList<String>(Arrays.asList(trimmed.split(","))); // now have an ArrayList containing "foo", "bar" and "baz"
Note, this is untested code.
Also, if it is not the case that your original ArrayList is a list of Strings, and is instead say, an ArrayList<MyDomainObject>, this approach will not work. For that your should instead find how to serialise/deserialise your objects correctly - toString is generally not a valid approach for this. It would be worth updating the question if that is the case.
You can't directly cast a String to ArrayList instead you need to create an ArrayList object to hold String values.
You need to change part of your code below:
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
to:
ArrayList<String> userCredentialsList = ( ArrayList<Strnig> ) session.getAttribute( attributeName );
if ( userCredentialsList == null ) {
userCredentialsList = new ArrayList<String>( 10 );
session.setAttribute(attributeName, userCredentialsList);
}
userCredentialsList.add( value );
How can I fix this:
class Name {
public void createArray(String name)
{
String name=new String[200];//we know, we can't do this- duplicate local variable,need a fix here.
}
}
I want to create array of strings with name of array as input parameter = name,
Example:
1) for function call createArray(domain1) -> I need essentially this to happen-> String domain1=new String[200];
2)for function call createArray(domain22)-> I need function to create String domain22=new String[200];
Hope this edit helps.
NOTE: There is a possibility that same name is passed byfunction twice/thrice. like createArray(domain1);, at that point of time I want to ignore the creation of array.
Store your new String[200] objects in a Map keyed by the name
Map<String, String[]> myarrays = new HashMap<String, String[]>();
myarrays.put("name", createArray("name"));
myarrays.put("test", createAray("test"));
then when you want one of them do
String[] data = myarrays.get("test");