Java collection
I have two Array list one is lstreminder, and other is lstpresent, there is code below for more specification:
lstintprsnt = new ArrayList<Integer>();
lstreminder = DAORemider.getLatestReminder(u.getName());
if (lstpresent == null || lstpresent.isEmpty()) {
lstpresent = lstreminder;
System.out.println("i m in if" + lstpresent);
} else {
System.out.println("i m in else" + lstpresent.size());
lstreminder.removeAll(lstpresent);
/* at this position listreminder will be empty and do not execute loop,
but still it hold values and executed loo, but if I try this with
an Integer arraylist then its work fine, means it not executed
loop, because it doesnt have any value */
for (Reminder r : lstreminder) {
System.out.println("lst" + r.getReminderid());
lstpresent.add(r);
}
System.out.println("i m in else" + lstpresent);
}
System.out.println("out " + lstpresent);
ServletActionContext.getContext().getSession().put("lstpresent", lstpresent);
lstpresent.clear();
Yes, assignment will just copy the value of lstreminder (which is a reference) to lstpresent . They will both refer to the same object.
Creating a copy is pretty easy though:
List lstpresent = new ArrayList(lstreminder );
Related
I am having an issue with my method below. I am expecting it to compare an inputted parameter against a collection of items. As my code is now it will only return true meaning it will only find the item in the collection if it is of type string, null, or int that is two characters or less. I would like my method to be able to find variables of any type. For example, in my test, I add 0.5 to the collection and pass a parameter of 0.5 to my method. Even though 0.5 is in the collection my method still returns false meaning it can't be found in the collection. I suspect the reason I am not able to find parameters of any type is because of something happing with their type when passing them to the parameter and the collection.
I have been messing around with this code for hours now and still can't figure out what the issue is. If you have any ideas or tips I would love to hear them. Thanks.
My Method:
public boolean contains(Object arg0) {
// For loop that searchs are current collection for arg0
for (Object c : data) {
if (arg0 == null) {
System.out.println(arg0 + " value");
return true;
} else if (arg0.equals(c)) {
System.out.println("found " + c + " and " + arg0);
return true;
} else {
System.out.println("couldint find " + arg0);
return false;
}
}
return false;
Test for method:
#SuppressWarnings("unchecked")
#Test
void testToSortedList()
{
ArrayCollection arrayCollection = new ArrayCollection();
ArrayCollection resultArray = new ArrayCollection();
// add the objects to the collections
arrayCollection.add("Test");
resultArray.add(771);
resultArray.add(.5);
System.out.println(resultArray.addAll(arrayCollection));
System.out.println(resultArray.contains(771));
System.out.println(resultArray.contains(.5));
System.out.println(resultArray.contains("Test"));
}
I have a method which needs to add the provided bank account to an array which I have created:
public boolean addAccount (BankAccount newAccount[]) {
if (numAccounts == 0) {
return false;
}
else {
return true;
for(int counter=0; counter<newAccount.length; counter++)
newAccount[counter] += accounts;
}
}
it is tested by this method:
public static boolean test5() {
System.out.println("Test5: add an account to a customer.");
BankAccount b = new BankAccount();
Customer c1 = new Customer("Alice", "Smith");
customerCounter ++;
if (!c1.addAccount(b))
return false;
return c1.toString().equals("Alice Smith, " + c1.getCustomerID() + "\n" + b.toString() + "\n");
}
However I am getting an error which eclipse does not have a solution for in this line:
newAccount[counter] += accounts;
First of all you need to improve the code quality. Re-design your function and data structure.
In the addAccount function, where did you derive/manipulate 'numAccounts'?
In method parameter, use List instead of array 'BankAccount newAccount[]'. Use like (List accounts). Then you can use accounts.add() method.
what is the definition of 'accounts'?
Do you really need to return anything from this method?
after return statement, no code will be executed. move 'return' statement as the last statement.
Paste the full code to get idea about overall structure.
If u just want to see how a new value can be added to an array then here it is...
int myArray[]={10,20,30};
int newNumber=200; //new value to be added
/*Size of an array doesn't change once it is initialized,so a new Array must be
created (with new Size )to add new values.*/
int newArray[]=new int[myArray.length+1];
//The newArray will have {0,0,0,0};
// Now copy all the data from previous array to new array.
for(int i=0;i<myArray.length;i++)
newArray[i]=myArray[i];
//Now the content of newArray is {10,20,30,0}
newArray[newArray.length-1]=newNumber;
//Now the final content of newArray is {10,20,30,200}.
Now,Having said that, I agree with #Turing85 and #Shafiul.With your above code,you will eventually get unreachable code and also Type Incompatible errors and yes,kindly redesign your code.
In my continuing education on Arrays and ArrayLists I'm trying to smarten up my code by passing an ArrayList from one method to another. Here is my code:
public void exampleArrayList () {
ArrayList<String> al = new ArrayList<String>();
al.add("AZ");
al.add("BY");
al.add("CX");
al.add("DW");
al.add("EV");
al.add("FU");
al.add("GT");
display(al);
}
public void display(ArrayList al) {
System.out.println("Index of 'AZ': " + al.indexOf("AZ"));
System.out.println("Index of 'FU': " + al.indexOf("FU"));
System.out.println("Index of 'AA': " + al.indexOf("AA"));
System.out.println("Index of 'CX': " + al.indexOf("CX"));
// for (String row : al)
// System.out.println("Value at Index " + al.indexOf(row) +
// " is " + al.get(al.indexOf(row)));
for(int i = 0; i < al.size(); i++)
System.out.println("Value at Index " + al.indexOf(i) +
" is " + al.get(al.indexOf(i)));
}
In the display method works with both for statements commented out. The for statement that is currently commented out doesn't work because row is looking for a String but get's assigned an object even although array al is a string. Do I need to cast al into a string or something? This is not the case when I run the for loop when the loop is in the same method that created the ArrayList in and I don't understand the difference.
The second for statement that isn't commented out causes a crash giving me the following runtime error:
java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1
I tried changing the i < al.size() to a hard coded number and it still failed and I don't know why.
1) You need to pass it as an ArrayList<String>:
public void display(ArrayList<String> al) {
^^^^^^^^
2) You're searching for the integers in the list. The list doesn't contain any integers, so indexOf returns -1. Then you call al.get(-1) where -1 is obviously out of bounds. I'm not sure what you meant to do here.
You are using indexOf(), which, given an int, will search for that int and return its index if the list contains it. As this isn't the case - it is a List<String> - you get index out of bounds because you are trying to retrieve an element at index -1. -1 is returned from indexOf() if the element can't be found, which it can't.
This is why you shouldn't use raw types. Use get() and a List<String> as your parameter (no need to make it specifically ArrayLists):
System.out.println("Value at Index " + i +
" is " + al.get(i));
and
public void display(ArrayList<String> al) {
One other thing to "smarten the code" is to not use the specific implementation in the declaration or parameters.
public void exampleArrayList () {
// use the interface List<T>, not the specific implementation ArrayList<T>
List<String> al = new ArrayList<String>();
...
}
// take the Interface, and give it the type
public void display(List<String> al) {
....
}
The functionality will be the same, but it is a better programming approach to program to interfaces rather than implementations.
EDIT: Also, unless you really need the index for some reason, using the enhance for loop may be more appropriate
for (String s : al) {
//some operation
}
How I can get those values from this object? I was trying to getFields, getDeclaredFields etc. but everything is empty.
The problem is that Field[] myField = o.getClass().getDeclaredFields(); always return an empty array.
I am getting those values from database this way:
Query reqDisplayResponse = em.createNativeQuery("Select * FROM pxds_displayResponse");
List<Object> displayResponseList = reqDisplayResponse.getResultList();
And I want to print those values:
for(Object o: displayResponseList) {
for(Field field: o.getClass().getDeclaredFields()) {
log.info(field.getName());
}
}
Unfortunately log.info is unreachable.
Ok, here is solution. In fact object is an array, getDeclaredFields() return empty table, in documentation we can read:
If this Class object represents an array type, a primitive type, or void, then this method returns an array of length 0.
So in this situation it is useless. All we have to do is iterate over this object this way:
for(Object o: displayResponseList) {
for(int i = 0; i < 7; i++) {
System.out.println(((Object[])o)[i].toString());
}
System.out.println("...............");
}
Hope this will help someone in future.
You should use getDeclaredField, and then use get on it, passing the object as parameter.
Like this:
Field myField = object.getClass().getDeclaredField("_myField");
myField.setAccessible(true);
return (Integer) myField.get(object);
Try to display the object 'o' like an array:
for(int index = 0 ; index < 10 ; index++){
Log.info(String.valueOf(o[index]));
}
I think those fields you are trying to access are private
So in order to access private fields you have to:-
for (Field f : object.getClass().getDeclaredFields()) {
f.setAccessible(true);
Object o;
try {
o = f.get(object);
} catch (Exception e) {
o = e;
}
System.out.println(f.getGenericType() + " " + f.getName() + " = " + o);
}
This is an ID given by the Eclipse debugger, not by Java. You cannot access it.
There is System.identityHashCode(Object) to get the Object identity. (not the same ID)
If you want an ID like the one shown in the Eclipse debugger, you'd have to allocate them yourself.
Here is some general direction how you could do something like that:
Elegant way to assign object id in Java
Gwozdz, I think I understand your question. If I understood correctly, you are having problemas to access the value from a list of objects, in your image code example I'm seeing that you are using List. Try to use List<Object[]> and then use a foreach to access every value of your matrix.
List<Object[]> displayResponseList = reqDisplayReponse.getResultList();
foreach(.....){
foreach(.....){
[manipulate you object value here]
}
}
Just for your information: Matrix is a list of lists. In that case a list of array.
I've been trying to get this code to work for what feels like an age at this stage. it is meant to compute prime numbers in a range, and I've written a method to print them. Unfortunately the code will not compile, citing the warning:
"warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.List"
--I understand from googling that this warning is for not declaring what types of values should be in your erray, but I have done this, and the error only seems to come about when I try to use the .add() function on my array list.
and when I try to run it it gives a somewhat more scary error of
"Static Error: Undefined name 'PrimeNumbers'
I think I've gone code-blind at this point and despite several attempts cannot find out what I am doing wrong.
import java.util.*;
public class PrimeNumbers {
private List listOfPrimeNumbers; //add a member variable for the ArrayList
public static void main(String args []){
PrimeNumbers primeNumberList = new PrimeNumbers(50);
primeNumberList.print(); //use our new print method
}
public PrimeNumbers (int initialCapacity) {
listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity/2); //initialCapacity/2 is an easy (if not tight) upper bound
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
while (start != initialCapacity)
{
if (isPrimeNumber[start])
{
listOfPrimeNumbers.add(start);
//add to array list
numberOfPrimes++;
for (int i = start; start < initialCapacity; i+=start)
{
isPrimeNumber[i] = false;
}
}
start++;
}
}
public void print() //add this printout function
{
int i = 1;
Iterator iterator = listOfPrimeNumbers.listIterator();
while (iterator.hasNext())
{
System.out.println("the " + i + "th prime is: " + iterator.next());
i++;
}
//or just System.out.println(listOfPrimeNumbers);, letting ArrayList's toString do the work. i think it will be in [a,b,c,..,z] format
}
public List getPrimes() {return listOfPrimeNumbers;} //a simple getter isnt a bad idea either, even though we arent using it yet
}
Change this line
private List listOfPrimeNumbers; //add a member variable for the ArrayList
to
private List<Integer> listOfPrimeNumbers; //add a member variable for the ArrayList
This will elimiate the warning.
Bonus - you may want to use the enhanced for loop inside the print method as an alternative approach:
public void print() {
int i = 1;
for (Integer nextPrime:listOfPrimeNumbers) {
System.out.println("the " + i + "th prime is: " + nextPrime);
i++;
}
}
You've decalred primeNumbers to be an untyped List but then created an ArrayList of Integer. Change the declaration of primeNumbers to:
private List<Integer> listOfPrimeNumbers;
The for loop you are using to set all the isPrimeNumber to true doesnt work, the condition should be i<=initialCapacity or even better use:
Arrays.fill(isPrimeNumber, true);
In your print method I wouldnt bother using an iterator and keeping track of the int i, just use a normal for loop.
Without knowing what command you are using to build the code and then try and run it, it is hard to diagnose your runtime error. Make sure your command window is in the same directory as your .class file.