converting from Object to string in java - java

I have this below method
public List<Object> ProductbyJobcode (String jobcode)
{
List<Object> temp = new ArrayList<Object>();
temp = riskJobCodeProductMappingDAO.fetchProductByJobCode(jobcode);
return temp;
}
and i am taking the input in the Object list from the above method into Object type of list
List<Object> temp = new ArrayList<Object>() ;
temp = ProductbyJobcode(jobcode);
now i am trying to retrieve the value into string but i am getting exception, please advise how to achieve the same how i will convert the object to string
String Product ;
String Actiontype;
for (int i = 0; i < temp.size(); i++) {
product = temp.get(0).toString();
Actiontype = temp.get(1).toString();
}

Object.toString() could provide NPE. So more suitable method is String.valueOf().
String Product = temp.size() >= 1 ? String.valueOf(temp.get(0)) : null;
String Actiontype = temp.size() >= 2 ? String.valueOf(temp.get(1)) : null;

Well this
for (int i = 0; i < temp.size(); i++) {
product = temp.get(0).toString();
Actiontype = temp.get(1).toString();
}
doesn't really test the bounds of the list correctly; you might only have one String in the list, which will mean temp.get(1) throws an IndexOutOfBoundsException.
It's not clear what exactly you're trying to achive, but this should work:
for (int i = 0; < temp.size; i++) {
System.out.println(temp.get(0));
}
If you really need the two items, you probably want something like this
product = (temp.isEmpty()) ? null : temp.get(0).toString();
actionType = (temp.size() > 1) ? temp.get(1).toString() : null;

The problem is that if your temp list contains only 1 element you try to get second element in this line:
Actiontype = temp.get(1).toString();
That cause:
java.lang.IndexOutOfBoundsException
Because you try to get second element when the list contains only one

Related

class software.amazon.awssdk.services.s3.model.CommonPrefix cannot be cast to class java.lang.String

I have fetched all the common prefix from S3 and now i want to store these common prefix in fixed size array of String, so i tried to loop over the List and tried to cat the element into Stirng but it doesnt allow me to do the same.
String bucketName = s3BucketDetails.getBucketName();
String bucketPath = s3BucketDetails.getBucketPrefix();
VehicleHeaderImage vehicleHeaderImage = null;
List<S3Object> objList = new ArrayList<>();
S3ResponseMessage response = null;
String[] array;
int index = 0;
try {
List<CommonPrefix> allKeysInDesiredBucket = listAllKeysInABucket(bucketName, bucketPath);
array = new String[allKeysInDesiredBucket.size()];
for (Object value : allKeysInDesiredBucket) {
array[index] = (String) value;
index++;
}
// for (int i = 0; i <= array.length - 1; i++) {
objList = s3Service.getBucketObjects(bucketName, array[1]);
// }
if it is not possible then how do I fetch the common prefix from List<CommonPrefix>
There is a public method on the CommonPrefix object called prefix() which returns a String — that might be what you are looking for.
S3 sdk reference: https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/model/CommonPrefix.html

ArrayList Cast in java Combo box

Hi there i have this code
public void comboCountry(List<Countries> cs) {
country = db.fillComboCountries();
DefaultComboBoxModel dcbm = (DefaultComboBoxModel) CountryComboBox.getModel();
for (int i = 0; i < country.size(); i++) {
String row[] = new String[country.size()];
//row[i] = String.valueOf(country.get(i).getCountryId());
row[i] = country.get(i).getCountryName();
// row[i] = country.get(i).getCountryCode();
dcbm.addElement(row);
}
}
with country = db.fillComboCountries(); i query the database and load everything into an ArrayList.
The Arraylist is country.
When i load my data into combobox i get
[Ljava.lang.String;#fdfc58
how can i avoid that and get the value that i want?
I have try with Arrays.tostring(), but i get also [ ].
Instead of dcbm.addElement(row); use dcbm.addElement(country.get(i).getCountryName());
With this, you will add individual elements of an array rather than array itself. Also you would avoid creating arrays with every item in the country list.
You are creating a new String array in each iteration, you should initialize the array before the for loop:
String row[] = new String[country.size()];
for (int i = 0; i < country.size(); i++) {
...
}
If you only want to add the countryName in each iteration, you don't need the array at all:
for (int i = 0; i < country.size(); i++) {
String countryName = country.get(i).getCountryName();
dcbm.addElement(countryName);
}
Or:
for (Country c : country) {
dcbm.addElement(c.getCountryName());
}

Java - removing object from Array

I need to create a method to remove an element from an array of objects, without turning it into an ArrayList.
This is the constructor for my object:
public Person(String name1, String telno1)
{
name = name1;
telno = telno1;
}
And my Array:
int capacity = 100;
private Person[] thePhonebook = new Person[capacity];
And i have a shell for my remove method:
public String removeEntry(String name)
{
//name is name of the person to be removed (dont worry about duplicate names)
//returns the telephone number of removed entry
}
Im not sure how to delete the element in the array (i dont want to just set the values to null)
I did think of creating a new array and copying parts on either side of the element to be removed to form a new array but im not sure how to implement that.
I also have a find method which can be used to find the name of the person in the array if that helps:
private int find(String name)
{
String name1 = name;
int i = 0;
int elementNo = 0;
int found = 0;
while(i < size)
{
if(thePhonebook[i].getName().equals(name1))
{
elementNo = i;
found = 1;
break;
}
}
if(found == 1)
{
return dirNo;
}
else
{
dirNo = -1;
return dirNo;
}
}
Thanks for your time.
You cannot directly remove an element from an array in Java. You two choices:
A. If you must preserve the order of the elements in the array: Begin at the index you want to remove, and shift each element "down" one index (toward index 0), as in:
public String removeEntry(String name)
{
String result = null;
int index = find(name);
if (index >= 0)
{
result = thePhonebook[index].telno;
for (int i = index + 1; i < thePhonebook.length; ++i)
{
thePhonebook[i - 1] = thePhonebook[i];
if (thePhonebook[i] == null)
{
break;
}
}
thePhonebook[thePhonebook.length - 1] = null;
}
return result;
}
In the above implementation, the value null in the array signifies the end of the list.
B. If the order of the elements in the array doesn't matter: Swap the element you want to remove with the last element of the list. Note that to do this you need to maintain a length value for the list, which is the value thePhonebookLength in the code below.
public String removeEntry(String name)
{
String result = null;
int index = find(name);
if (index >= 0)
{
result = thePhonebook[index].telno;
thePhonebook[index] = thePhonebook[thePhonebookLength - 1];
thePhonebook[--thePhonebookLength] = null;
}
return result;
}
A benefit of both of these solutions is that the array is modified in place, without using allocation.
Having offered these possibilities, I suggest that using a collection is better suited for your purposes -- such as one of the List subclasses, or perhaps even a Map if lookups by name are common.
To do this is to get the last index in your array and then pass it to the one that was just deleted and the delete the last array.. if the array is the last one dont it just delete it..
for(int i = 0; i < thePhonebook .length; i++)
{
if(thePhonebook[i].getName().equals(string))
{
if(i == thePhonebook .length - 1)
thePhonebook[i] = null;
else
{
thePhonebook[i] = null;
thePhonebook[i] = thePhonebook[thePhonebook .length - 1];
thePhonebook[thePhonebook .length - 1] = null;
}
}
}

Detail formatter error: java.util.Arrays cannot be resolved to a type

I have developed a BlackBerry application where in I am reading in a HEX String values. The values returned are as follows:
String result = response.toString();
where result is:
["AC36C71DF3CB315A35BFE49A17F483B6","CF5B717ACC460E3C4545BE709E9BCB83","E1EE334738CA4FA14620639DD6750DC3","DD40E2822539C2184B652D1FC3D2B4E6","6AF4B1EAC8D8210D64A944BFD487B9F2"]
These are passed into the following split method to separate the values. The method is as follows:
private static String[] split(String original, String separator) {
Vector nodes = new Vector();
int index = original.indexOf(separator);
while (index >= 0) {
nodes.addElement(original.substring(0, index));
original = original.substring(index + separator.length());
index = original.indexOf(separator);
}
nodes.addElement(original);
String[] result = new String[nodes.size()];
if (nodes.size() > 0) {
for (int loop = 0; loop < nodes.size(); loop++) {
result[loop] = (String) nodes.elementAt(loop);
System.out.println(result[loop]);
}
}
return result;
}
The above array is passed is as the String original in the method. This part is working fine. However, when a single value is passed in as String original, i.e. ["6AF4B1EAC8D8210D64A944BFD487B9F2"], I get an error :
Detail formatter error:java.util.Arrays cannot be resolved to a type.
Please help !!! The values posted above are exact values as read including the parenthesis [] and quotations ""
The Blackberry libraries are based on Java ME and not Java SE. In Java ME some classes have been removed to reduce the runtime footprint such as the Arrays class.
Take a look at the Blackberry JDE java.util package, see there is no Arrays class. So in your code you cannot use methods coming from the Arrays class, you must found a workaround or implement the feature yourself.
Try this split method -
public static String[] split(String strString, String strDelimiter) {
String[] strArray;
int iOccurrences = 0;
int iIndexOfInnerString = 0;
int iIndexOfDelimiter = 0;
int iCounter = 0;
//Check for null input strings.
if (strString == null) {
throw new IllegalArgumentException("Input string cannot be null.");
}
//Check for null or empty delimiter strings.
if (strDelimiter.length() <= 0 || strDelimiter == null) {
throw new IllegalArgumentException("Delimeter cannot be null or empty.");
}
if (strString.startsWith(strDelimiter)) {
strString = strString.substring(strDelimiter.length());
}
if (!strString.endsWith(strDelimiter)) {
strString += strDelimiter;
}
while((iIndexOfDelimiter = strString.indexOf(strDelimiter,
iIndexOfInnerString)) != -1) {
iOccurrences += 1;
iIndexOfInnerString = iIndexOfDelimiter +
strDelimiter.length();
}
strArray = new String[iOccurrences];
iIndexOfInnerString = 0;
iIndexOfDelimiter = 0;
while((iIndexOfDelimiter = strString.indexOf(strDelimiter,
iIndexOfInnerString)) != -1) {
strArray[iCounter] = strString.substring(iIndexOfInnerString,iIndexOfDelimiter);
iIndexOfInnerString = iIndexOfDelimiter +
strDelimiter.length();
iCounter += 1;
}
return strArray;
}

removing the value from a object in java or android

private String[] userKeys;
userKeys = MHConstants.friendsModelDetails.keySet().toArray( new String[MHConstants.friendsModelDetails.size()]);
if(MHConstants.friendsModelDetails.size()>0 ){
for(int i = 0;i<MHConstants.friendsModelDetails.size();i++){
String username = userKeys[i];
System.out.println("userkey contains"+username);
}
String number=9;
THis prints
1
5
9
8
10
How can i get the position of the value which is equal to ''number'' and delete that from userskey...
thanks in advance.
You can try Apache Commons
userKeys = ArrayUtils.removeElement(userKeys , number);
Or just iterating through array and shifting elements can do the same.
Something like (Its ugly and not tried/tested)
String number = "9";
boolean flag = false;
int j;
int length = userKeys.length;
for (int i = 0; i < length; i++) {
if(number.equals(userKeys[i])){
flag = true;
j = i;
}
}
if(flag){
for(int i=j;i<length-1;i++){
userKeys[i+1] = userKeys[i];
}
userKeys[length] = null; // resetting the value
}
Consider using a List instead of an Array. Then use an Iterator which will allow you to remove the element.
List<String> values = ...;
Iterator<String> iterator = values.iterator();
while(iterator.hasNext){
String next = iterator.next();
if (number.equals(next))
iterator.remove();
}

Categories