which one is the best way to access static elements? Lets say that I have a class which will serve to share an static array of int.
option A
final class A {
static private int[] a;
static {
a = new int[1000];
for(int i = 0; i < a.length;i++) {
a[i] = i*50;
}
}
static int getA(int index) {
int tmp = a[index];
return tmp;
}
}
option B
final class B {
static private int[] b;
static int getB(int index) {
b = new int[1000];
for(int i = 0; i < b.length;i++) {
b[i] = i*50;
}
int tmp = b[index];
return tmp;
}
}
Access
public class Test {
public static void main(String[] args) {
int numA = A.getA(50);
System.out.println(numA);
int numB = B.getB(50);
System.out.println(numB);
}
}
Which one is the best in term of performance. Or is exactly the same thing;
thank in advance
The obvious difference between the A and B classes is that in the case of the latter, the int[] array would be initialized every time the getter is called. In the absence of further requirements, this seems unnecessary. So, I vote for using the A class implementation.
A is better than B. In B, each time the getB function is called, a new int[] is created, which will cost both time and memory space in heap. Also the for loop in getB may be executed multiple times.
Related
So I have this code in the main class
public class OneDArrays
{
public static int[] create (int size)
{
int[] a1 = new int[size];
for (int i = 0; i < size; i++)
{
a1[i] = i*2+1;
}
return a1;
}
public int sumSome (int[] b1, int howmany)
{
int sum = 0;
if (howmany <= b1.length)
{
for (int i = 0; i < howmany; i++)
{
sum = sum + b1[i];
}
}
else
{
sum = -1;
}
return sum;
}
public int[] grow (int[] c1, int extra)
{
int[] newArray = new int[c1.length+extra];
for (int i = 0; i < newArray.length; i++)
{
while (i <= c1.length)
{
newArray[i] = c1[i];
i++;
}
newArray[i] = 0;
}
return newArray;
}
public void print (int[] d1)
{
for (int i = 0; i < d1.length; i++)
{
System.out.println (d1[i] + ", ");
}
}
}
And then I have my tester class,
public class OneDArraysTester
{
public static void main (String[] args)
{
int[] test1;
test1.create (5);
}
}
How do retrieve the method from the first class? I get the error that "create" is an undeclared method. If the "create" method were a constructer, I know I could just type create test1 = new create (5) but I don't see a way to turn it in to a constructer, so what's the way of doing that but for a method?
You invoke a static method with the classname. Literally className.methodName. Like,
int[] test1 = OneDArrays.create(5);
You have made a class named OneDArrays so you can call it's methods by creating an instance or object of that class.
like this :
OneDArrays ObjectOfClass = new OneDArrays();
int test1[] = ObjectOfClass.create(5);
similarly you can also call other methods of that class by accessing methods of this newly created object ObjectOfClass.
like :
sumOfArray = ObjectOfClass.sumSome(test1,3);
int biggerTest1[] = ObjectOfClass.grow(test1,10);
If you want to make create method works as a constructor than you can but you cannot return value from a constructor so you cannot return your array from that constructor.
Since you have declared the create method as static, #ElliotFrisch is the best way. But, it is not always a good idea to make methods static. So another way to achieve what you want would be to make the create method non-static.
public int[] create (int size){/*Method Body*/};
And then create an object of the OneDArray class to access the method.
OneDArrays oneDArrays = new OneDArrays();
int[] test1 = oneDArrays.create(5);
or,
int[] test1 = new OneDArrays().create(5);
I have created a class using linked list to display 20 Fibonacci numbers. Here is my code:
import java.util.LinkedList;
public class FibonacciLinkList {
private LinkedList<Integer> fibonacciList;
public FibonacciLinkList(LinkedList<Integer> FibonacciLinkList) {
this.fibonacciList = FibonacciLinkList;
}
public LinkedList<Integer> sum()
{
int n, a = 0, b = 0, c = 1;
for(int i = 1; i <= 20; i++)
{
a = b;
b = c;
c = a + b;
}
return fibonacciList;
}
public void display() {
System.out.println(fibonacciList);
}
public static void main(String[] args) {
LinkedList fibonacciList = new LinkedList();
fibonacciList.display(); //This is where the error is
}
}
The problem I am having is displaying the Fibonacci numbers on the console.
I have tried to do this by using a display method but it hasn't really worked for me. I have done a lot of searching online and on SO and have tried them but they have not worked for me. It would be appreciated if you could fix my code so that it does work.
I am new to linked list and this is the first time I am coding a linked list myself and I feel that a solution to this problem will help me understand linked lists better.
As I mentioned, LinkedList is not an instance of FibonacciLinkedList, and it does not possess the display() method. Attempting to invoke it on the LinkedList object will lead to failure to compile.
The sum() method is not invoked nor does it actually do anything. That is, it does not assign anything to the fibonacciList you have.
I would recommend that you extend the LinkedList class and generate the items on instantiation. Then, using the default toString() you can display to console. After all, the class is simply an extension of the LinkedList data structure to store Fibonacci numbers up to 20.
As you extend LinkedList, you inherit the AbstractCollection.toString() method for which the "string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]")."
public class FibonacciLinkedList extends LinkedList<Integer> {
public FibonacciLinkedList(int n){
int a = 0, b = 0, c = 1;
for(int i = 1; i <= n; i++) {
a = b;
b = c;
c = a + b;
this.add(c);
}
}
public void display() {
System.out.println(this.toString());
}
public static void main(String[] args) {
FibonacciLinkedList list = new FibonacciLinkedList(20);
list.display();
}
}
I fixed your code:
import java.util.LinkedList;
public class FibonacciLinkList {
private LinkedList<Integer> fibonacciList;
public FibonacciLinkList() {
this.fibonacciList = new LinkedList<Integer>();
}
public LinkedList<Integer> sum()
{
int n, a = 0, b = 0, c = 1;
for(int i = 1; i <= 20; i++)
{
fibonacciList.add(a);
a = b;
b = c;
c = a + b;
}
return fibonacciList;
}
public void display() {
System.out.println(fibonacciList);
}
public static void main(String[] args) {
FibonacciLinkList fibonacciList = new FibonacciLinkList();
fibonacciList.sum();
fibonacciList.display();
}
}
Try this.
There is several points that you need to take care :
sum() is never called.
the look in sum() does not change fibonacciList, it only uses local variables and does nothing else with it.
display() is NOT a LinkedList function, so it will likely not work. And even if it were working, it will likely not display what you expect : you need to loop through the list and print each value.
an other fibonacciList is created in the main function, so the display (if it was working) would show the content of this local list and not the global one.
I am in process of learning immutability but I am not able to exactly digest how this works. So in order for me to understand immutability, I created a test program.
The funtion getArray(Box b) will make an ArrayList of Box objects.
Expected output: Actual output:
Output Output
a is 5 a is 5
b is 10 b is 10
Output Output
a is 0 a is 4
b is 0 b is 40
Output Output
a is 1 a is 4
b is 10 b is 40
Output Output
a is 2 a is 4
b is 20 b is 40
Output Output
a is 3 a is 4
b is 30 b is 40
Output Output
a is 4 a is 4
b is 40 b is 40
Logic:
public class Box {
static int a;
static int b;
public Box() {
a = 5;
b = 10;
}
public int getA() {
return a;
}
public void setA(int x) {
a = x;
}
public int getB() {
return b;
}
public void setB(int x) {
b = x;
}
public void display() {
System.out.println("Output");
System.out.println("a is " + a);
System.out.println("b is " + b);
System.out.println();
}
}
Main Class
import java.util.ArrayList;
public class Check {
public static void main(String[] args) {
Box b = new Box();
b.display();
ArrayList<Box> arr2 = new ArrayList<Box>();
arr2 = getArray(b);
for (int i = 0; i < arr2.size(); i++) {
arr2.get(i).display();
}
}
public static ArrayList<Box> getArray(Box b) {
ArrayList<Box> arr = new ArrayList<Box>();
for (int i = 0; i < 5; i++) {
b.setA(i);
b.setB(i * 10);
arr.add(b);
}
return arr;
}
}
How do I change the logic in such a way that I get the desired output? How do we decide how and where to edit the code to ensure immutability?
This would be an immutable:
public final class Box {
final int a;
final int b;
public Box(int a, int b) {
this.a = a;
this.b = b;
}
}
And then your array method would be:
public static ArrayList<Box> getArray(Box b) {
ArrayList<Box> arr = new ArrayList<Box> ();
for(int i =0 ;i <5; i++) {
arr.add(new Box(i, i*10));
}
return arr;
}
The data members are declared final because they're immutable, and so getters are pointless and setters just make no sense.
The class is declared final so you cannot subclass it.
In short, an immutable object is an object whose state cannot be modified after it's created. Your immutable Box object would look like this:
public final class Box {
private final int a;
private final int b;
public Box(int a, int b) {
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
public void display() {
System.out.println("Output");
System.out.println("a is " + a);
System.out.println("b is " + b);
System.out.println();
}
}
Notice that the variables a and b are assigned exactly once, during the construction of the Box instance. There are no setters, because Box's immutability means that its state (including variables a and b) will not change over its lifetime.
The final keyword in front of a and b means that you must assign them exactly once. It's actually considered good practice to make all your variables final unless you specifically need them not to be; but for an immutable object it's essential.
You were using the static keyword. Static has nothing to do with immutability. It means the variable is shared among all instances of the Box class. In my example, each Box instance has its own copies of a and b, because I didn't make them static.
To wrap this up, I'll give an example of your main class which has the desired output:
public class Check {
public static void main(String[] args) {
final List<Box> arr2 = getArray();
for (int i = 0; i < arr2.size(); i++) {
arr2.get(i).display();
}
}
public static ArrayList<Box> getArray() {
final ArrayList<Box> arr = new ArrayList<>();
for (int i = 0; i < 5; i++) {
final Box box = new Box(i, i * 10);
arr.add(box);
}
return arr;
}
}
Note that a new instance of box is created at every iteration of the loop.
I'm trying to get a radix sort going with an array of queues to avoid long rambling switch statements but I'm having some trouble getting the array properly initialized. The constructor and an example of an implementation are given below.
I'm just getting a cannot find symbol error when I try to compile though.
public static radixj(){
IntQueue[] buckets = new IntQueue[10];
for (int i = 0; i < 10; i++)
buckets[i] = new IntQueue();
}
public static void place(int temp, int marker)
{
int pos = temp % marker;
buckets[pos].put(temp);
}
I'm pretty sure it is a really simple mistake that I'm making but I can't find it. Any help would be greatly appreciated.
In your code
IntQueue[] buckets = new IntQueue[10];
is a local variable to the function
public static radixj()
which must have a return type
public static void radixj()
So then you can't use it in another function
buckets[pos].put(temp);
You should declare a static class variable
class Foo {
static IntQueue[] buckets = new IntQueue[10];
...
and access it using: Foo.buckets
class Foo {
public static IntQueue[] buckets = new IntQueue[10];
public static void radixj() {
for (int i = 0; i < 10; i++) {
Foo.buckets[i] = new IntQueue();
}
}
public static void place(int temp, int marker) {
int pos = temp % marker;
Foo.buckets[pos].put(temp);
}
}
the return type in radixj() is missing and buckets cannot be resolved to a variable
I am trying to return two numbers from this method. I thought this was correct. Where am I going wrong?
public int[] getDimension() {
int shapeWidth = 0;
int shapeHeight = 0;
// .....
int[] result = new int[] {shapeWidth, shapeHeight};
return result;
}
And then at a calling site, is this correct?
public int getWidth() {
return getDimension()[0];
}
I am asking because I believe there's a bug but I don't see it.
That's fine. Short but complete program to demonstrate it working:
public class Test {
public static void main(String args[]) {
int width = getDimension()[0];
System.out.println(width);
}
public static int[] getDimension() {
int shapeWidth = 5;
int shapeHeight = 10;
int[] result = new int[] {shapeWidth, shapeHeight};
return result;
}
}
You can make the result declaration line slightly simpler, by the way:
int[] result = {shapeWidth, shapeHeight};
Rather than using an array, I would recommend using a class
class Dimensions {
private int width;
private int height;
public Dimensions(int width, int height) {
this.width = width;
this.height = height;
}
// add either setters and getters
// or better yet, functionality methods instead
}
This will give you compile time referential integrity, which is much better than inferring based on "we know index 0 is width and index 1 is height".
If you still want to use an array, Jon's answer is spot on.
Your code looks fine, but try not to use an array if you only need a pair.
Since Java doesn't have tuples/pairs you have to implement them, but it's pretty easy. Refer to this question for a possible implementation.
public class Test {
public static void main(String args[]) {
int width = getDimension().getLeft();
System.out.println(width);
}
public static Pair<Integer, Integer> getDimension() {
int shapeWidth = 5;
int shapeHeight = 10;
return new Pair<Integer, Integer>(shapeWidth, shapeHeight);
}
}
This is better than a Dimension class, because you can use it everywhere in your code.