where to initiate object in java - java

This question relates to my answer of another of my question.
The original question is here
Can anyone explain why the bad code fails in the way explained in the comments (by the wy it is in pseudo code)
// bad code
ResultSet rs = getDataFromDBMS("Select * from [tableName];");
//temp uses a collection member within it to hold a list of column names to data value pairs (hashmap<String,String>)
Object temp = new objectToHoldInfoFromResultSet();
// loop over the result set
while (rs.next)// for each row in the result set
{
for (int i = 1; i <= rs.getNumberColums; i++) {
temp.add(infoAboutColumn);
}
temp.printInfo();// always prints correct (ie current) info
//the print just takes the hashmap member and asks for a
//toString() on it
anotherObject(makeUseOf(temp));// always uses info from first
//iteration. Essentially grabs the hashMap member of temp, and puts
//this into another collection of type
//HashMap< HashMap<String,String>, temp> see the linked question
//for more detail.
}
// Seemingly each loop into the while the temp.doSomethingToData(); uses
// the temp object created in the first iteration
// good code
ResultSet rs = getDataFromDBMS("Select * from [tableName];");
// loop over the result set
while (rs.next)// for each row in the result set
{
Object temp = new objectToHoldInfoFromResultSet();// moving
// declaration
// of temp into
// the while
// loop solves
// the problem.
for (int i = 1; i <= rs.getNumberColums; i++) {
temp.add(infoAboutColumn);
}
temp.printInfo();// always prints correct (ie current) info
anotherObject(makeUseOf(temp));// also uses the correct (ie current)
// info.
}

We can't reliably answer this without knowing what temp.printInfo() and makeUseOf() are doing. It is easy to implement them to behave the way you describe though.
When you instantiate temp outside the loop, you will be using the same object throughout all iterations of the loop. Thus it is possible for it to gather data from each iteration (e.g. into a collection). And then it is possible for methods to get data accumulated in the current iteration, as well as from any previous iteration, which may cause problems if it was not intended.
So let's assume temp contains a collection and in each iteration a column from the resultset is added to it. Now if temp.printInfo() is implemented to print info about the last element in this collection, while makeUseOf() is implemented to do something with the first element in the collection, you get the behaviour you observed.
OTOH when you instantiate temp inside the loop, you will get a new, distinct object in each iteration, which won't "remember" any data from earlier iterations. Thus even with the implementations of temp.printInfo() and makeUseOf() outlined above, you will get correct results.

I am not sure why the one is good and the other bad. My guess (without knowing what objectToHoldInfoFromResultSet and the other methods behaviour are) is the following:
In the first instance, the "objectToHoldInfoFromResultSet" (should be capitalised) is created once and everytime
temp.add(infoAboutColumn);
is called, new record data is added to the object. I would guess that this info should be cleared for each record... otherwise you'll get a lot of duplication. The duplication is taken care of by re-initialising the holder object. I.e. (1 2 3 4 5 6) instead of the (1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6).
Without knowing more about the various propriety objects, there is not much more I can tell you.

Related

Permutations of ArrayList<Integer>

im working on a problem where i have to obtain all permutations of an arraylist of numbers. The only restriction is that any number cant start with 0, so if we have [0,1,2] we would obtain
[1,2,0]
[1,0,2]
[2,0,1]
[2,1,0]
i know how to do this with 3 loops but the thing is that i have to repeat this to different sets of numbers with differentes sizes, so i need one method that i can apply to different sets of numbers but i have no clue on how to do this. I imagine i have to used some kind of recursive function but i dont know how to implement it so the numbers cant start with a 0. Any ideas? please dont just post the code i want to understand the problem, thank you in advantage!!
Curious question! Interesting code kata.
I naively think I would have a recursive method that takes:
a list of the items currently chosen by the caller
a set of the items available for the callee
The method would iterate over the set to chose 1 more item and call itself with the list extended by this item, and the set reduced by this item. Upon return, remove from list, add back to set and go on with next item (take a defensive copy of the set of course).
If the current list is empty, the selected first item cannot be 0, as per your rules. If you must collect the permutations somewhere (not just print), a 3rd argument would be required for a collection or an observer.
The recursion obvioulsy stops when the available set is empty, at which point the permutation is sent to the collection or observer.
If items can repeat, you may have benefit from sorting them first in order to skip electing the same item again at a given position.
Beware this quires a recursion depth of N, for N items. But the danger is minimal because even with N=10000, it may not stackoverflow, but the CPU time to complete would be order(N!) (probably end of universe...)
You could solve this recursively as described here: Permutation of an ArrayList of numbers using recursion.
The only thing that is missing there is your restriction with the zeros, which could be solved somehow like this (the loop is taken from the example above):
for (List<Integer> al : myLists) {
// The part you need to add:
if (al.get(0) == 0) {
continue;
}
String appender = "";
for (Integer i : al) {
System.out.print(appender + i);
appender = " ";
}
System.out.println();
}
You basically check the first element of each permutation and skip the ones with a leading zero. The continue jumps to the next iteration of the loop and therefore to the next permutation.

about java recursion to create combination of string

The question was asking me to return set containing all the possible combination of strings made up of "cc" and "ddd" for given length n.
so for example if the length given was 5 then set would include "ccddd" and "dddcc".
and length 6 would return set containing "cccccc","dddddd"
and length 7 would return set contating "ccdddcc","dddcccc","ccccddd"
and length 12 will return 12 different combination and so on
However, set returned is empty.
Can you please help?
"Please understand extremeply poor coding style"
public static Set<String> set = new HashSet<String>();
public static Set<String> generateset(int n) {
String s = strings(n,n,"");
return set; // change this
}
public static String strings(int n,int size, String s){
if(n == 3){
s = s + ("cc");
return "";}
if(n == 2){
s = s + ("ddd");
return "";}
if(s.length() == size)
set.add(s);
return strings(n-3,size,s) + strings(n-2,size,s);
}
I think you'll need to rethink your approach. This is not an easy problem, so if you're extremely new to Java (and not extremely familiar with other programming languages), you may want to try some easier problems involving sets, lists, or other collections, before you tackle something like this.
Assuming you want to try it anyway: recursive problems like this require very clear thinking about how you want to accomplish the task. I think you have a general idea, but it needs to be much clearer. Here's how I would approach the problem:
(1) You want a method that returns a list (or set) of strings of length N. Your recursive method returns a single String, and as far as I can tell, you don't have a clear definition of what the resulting string is. (Clear definitions are very important in programming, but probably even more so when solving a complex recursive problem.)
(2) The strings will either begin with "cc" or "ddd". Thus, to form your resulting list, you need to:
(2a) Find all strings of length N-2. This is where you need a recursive call to get all strings of that length. Go through all strings in that list, and add "cc" to the front of each string.
(2b) Similarly, find all strings of length N-3 with a recursive call; go through all the strings in that list, and add "ddd" to the front.
(2c) The resulting list will be all the strings from steps (2a) and (2b).
(3) You need base cases. If N is 0 or 1, the resulting list will be empty. If N==2, it will have just one string, "cc"; if N==3, it will have just one string, "ddd".
You can use a Set instead of a list if you want, since the order won't matter.
Note that it's a bad idea to use a global list or set to hold the results. When a method is calling itself recursively, and every invocation of the method touches the same list or set, you will go insane trying to get everything to work. It's much easier if you let each recursive invocation hold its own local list with the results. Edit: This needs to be clarified. Using a global (i.e. instance field that is shared by all recursive invocations) collection to hold the final results is OK. But the approach I've outlined above involves a lot of intermediate results--i.e. if you want to find all strings whose length is 8, you will also be finding strings whose length is 6, 5, 4, ...; using a global to hold all of those would be painful.
The answer to why set is returned empty is simply follow the logic. Say you execute generateset(5); which will execute strings(5,5,"");:
First iteration strings(5,5,""); : (s.length() == size) is false hence nothing added to set
Second iteration strings(2,5,""); : (n == 2) is true, hence nothing added to set
Third iteration strings(3,5,""); : (n == 3) is true, hence nothing added
to set
So set remains un changed.

Which one is preferable? [duplicate]

This question already has answers here:
Time complexity for java ArrayList
(6 answers)
Closed 6 years ago.
I am getting arraylist.get(i) every time a loop executes more than three times within the loop.
Is it advisable or shall I store it in separate variable then use it again and again? Which one is preferable performance wise?
Setting it to a variable is slightly more efficient. Accesing arrayList.get (I) is O (1) but still costs something eventhough it is really minor and insignificant.
Setting it to a variable is more readable in my opinion.
It's always a good approach to write readable and maintainable code. Since you question is very broad so expect broad answers as well.
List<Integer> integerList = new ArrayList<>();
for (int i=0;i<integerList.size();i++) {
Integer integerValue = integerList.get(i);
// make sure integerValue is not null.
// Thanks #Tom for pointing this out
System.out.println (integerValue);
// Do operations
System.out.println (integerValue);
// Do more operations
System.out.println (integerValue);
}
Now this is one time assignment but you can use it at multiple times. Now, for instance, you have to change the logic of program so that you want to get always i+1, it will be easy for you to change only once, not multiple times.
As others mentioned, getting object one time is slightly more efficient. Of course most of times this won't produce any problems and you can't notice any differences.
Logically because it's an O(1) operation, it shouldn't cause any differences at all, but because it calls a function of an object of type ArrayList , It's less cache friendly and direct memory reference maybe needed. Still the difference is very little.
declaring and assigning a variable once like String myString = arraylist.get(i); will be marginally faster than calling arraylist.get(i) multiple times.
Once you've done this you can call any methods on the myString instance.
I assume that arraylist is of type ArrayList<String>.
you may want to include a null check in your loop as well:
for(int i = 0; i < arraylist.size(); i++){
String myString = arraylist.get(i);
if(myString != null){
//any calls to methods on myString
}
}

Array Length in Java - Performance [duplicate]

This question already has answers here:
What is the Cost of Calling array.length
(8 answers)
Java native array lengths
(6 answers)
Closed 9 years ago.
Let's say I create an array of ints with length 10, i.e.
int[] array = new int[10];
At some point in my code, I want to compare the value of an int variable, let's call it var, with the length of the array.
I would like to know if this piece of code:
if(var == array.length) { // stuff }
and this piece of code:
if(var == 10) { // stuff }
which do exactly the same thing, have also the same performance.
In other words, I would like to know the internal mechanics that the JVM (?) uses to find the length of the array (I don't say "to return" since length is a field, not a method). Does it make use of iteration? Because if it does, then the 2nd piece of code would be faster than the 1st one.
EDIT: Similar question regarding array.length cost (even though focusing more to its use in for loops):
What is the Cost of Calling array.length
.length is a property, so it would not do iteration for sure. Still, the value of the property is, naturally, fetched at runtime, meaning that the second solution will be a little bit faster (as this is comparison with constant).
Still the first implementation is far more preferable:
This makes your code quite more maintainable
You can alter the length of the array only at one place
You will never feel the performance difference unless you pass through this if litterally millions of times in a second.
EDIT By the way you can yourself tell this is a property - there are no braces after the call. I at least do not know of a way in java to make property access do additional computation, but just retrieving its value.
.length is a property of the array, not a function. Thus, the result would be available immediately, with no iteration necessary.
From the Java Doc
The members of an array type are all of the following:
The public final field length, which contains the number of components
of the array. length may be positive or zero.
length is an final field of array, so no iterations are required while writing following code.
if(var == array.length) { // stuff }
And it is good coding practice indeed.
The length property of an array is extracted in constant (O(1)) time - there is no iteration needed. It's also good practice to use this.

parallel processing with loop construct in java

I am working to create a crawler- a java web app, in which users can define crawl jobs, which extract and store information from specific websites.
As part of this work, there is a 'loop' construct... it has a list portion, which is evaluated initially (and typically represents a list of values)... After that is the loop body, which is executed once for each item in the list (from the list portion mentioned previously).
Note that there can be a loop construct within another loop construct, and so on.
The problem is, sometimes one list can contain millions of rows of data - and the body is to be executed for each row in this list. The body has a start index value, upper bound for the index, and is incremented by one.
What I want to do is, for a single level loop, initially calculate the list value and store it in database. After that, instead of executing the body in one go, split it up into different sections so that different sections of the list are processed in parallel.
However, how do I split up a job for an n-level loop? (Ie one loop within one loop and so on.)
Is there some recommended way of doing such processing... Any tutorial or guide you could point me to, would be very helpful for me.
I suggest packing the processing logic for 1 element of the list into a Runnable or Callable, and then pass them to an Executor for execution. This will run tasks in parallel in different worker-threads. Of course it depends on how many cores your machine has, how "parallel" this will really be.
If each element of the list can be processed completely independent of all the others, than this would be the way to go for me, instead of messing around myself with Threads and dividing the list into sublists etc.
According your description, i got that you are fetching the source code of xyz website and scrap data from that.
You can use XPath and RegularExpression to do this kind of task as its best. use JSOUP for that ,it helps you a lot.
As far as parallelization is concern you can use the .select , getElementbyId, getElementByClass of JSOUP (it's a opensource). than simply put a
for(i=0 ;i< length;i++)
{
i am fetching i;
i am fetching i+1;
int temp=i+1;
if(temp>=length)
{
break;
}
}
hope this helps: http://jsoup.org
This sounds like a great candidate for the Java 7 fork / join framework
Lets say you create 3 thread: T1, T2, T3. and following is the looping construct, for eaxmple
for(int i=0; i<100; i++)
{
for(int j=0; j<100; j++)
{
for(int k=0; k<100; k++)
{
// do some processing.
}
}
}
Modify the increment part as i += no. of threads. In this case it will be i += 3
Thus, the initial values of i, j, k will vary for each thread.
For T1: i = 0;
For T2: i = 1;
For T3: i = 2;
Similary the loop limit can be set.

Categories