This question already has answers here:
What's the best way to share data between activities?
(14 answers)
Closed 9 years ago.
I have a json file. So, I was parsed the json file and I stored all value in an ArrayList. Now, I want to share the value all the classes in application. So, what is recommended and efficient way to do that??
Singleton pattern.
just create a public static reference for your List object and access it from any part of your app. it will be accessible as long as your app is alive. and you can deallocate it manually (by nulling the reference).
public class SharedData {
public static List<Custom> jsonData;
}
and from any part of your application:
SharedData.jsonData = new ArrayList<Custom>();
and to read the data
Custom obj = SharedData.jsonData.get(0);
Singleton wiki
Now, I want to share the value all the classes in application. So, what is recommended and efficient way to do that??
Assuming that you missed out a preposition "with" in your above question and want to use your arraylist in all other classes as well, you might wanna go for a global Arraylist, which is nothing but declaring a public static Arraylist in a new class (let's call it GlobalState.java).
/** GLobalState.java **/
public class GlobalState {
public static ArrayList<E> jsonGlobalArrayList;
}
You can use getters & setters if you want.
Now, u can assign your arraylist to this global Arraylist as soon as u have populated your arraylist after parsing the json file.
GlobalState.jsonGlobalArrayList = jsonArrayList;
This is how I do it whenever I'm dealing with json values. Hope this helps.
P.S.: Excuse me for oversimplifying the solution this elaborately, as u might have understood this already when I mentioned about global ArrayList. :)
public class Utilities {
public static boolean boolVar = false ;
public static int intVar= 0 ;
public static String str = "" ;
public static List<Object> aList= new ArrayList<Object>() ;
public static HashMap<String, Object> aMap= new HashMap<String, Object>() ;
}
Use them by using class name like;
Utilities.boolVar = boolValue ; Utilities.intVar = intValue ;
inside activities.
Related
I'm wondering if I can declare an object in-line in Java like I can in JavaScript.
For example, in JavaScript I could say
let nameOfObject = {
anyKey: "my value",
someOtherValue: 5
};
console.log(nameOfObject.anyKey);// This logs "my value"
and this will create a classless object and assign nameOfObject as its "pointer" of sorts... How can I do this in Java? How do I create an object without a class?
I found one possible solution which looks like
Object nameOfObject = new Object(){
public String anyKey = "my value";
public int someOtherValue = 5;
};
System.out.println(nameOfObject.anyKey);
But that doesn't seem to compile, and says "anyKey cannot be resolved" and according to some other sources, will not work at all...
So I might be doing something very wrong, or maybe there's a different method, or maybe it's just straight up not possible with Java and I need to do it a different way...
class Some{
public String anyKey;
}
Some some = new Some() {
this.anyKey = "my value";
};
This code throws an error saying Syntax error, insert ";" to complete declaration, however
class Some{
public void anyMethod() {
}
}
Some some = new Some() {
public void anyMethod() {
System.out.println("Okay");
}
};
Works perfectly fine?
I don't understand what's going on here, but I would really appreciate an explanation and/or a solution (if one exists).
You can't really think of it as an "object" in Java. JavaScript objects are unique implementations of HashTables. If you want similar functionality, you can use a Java HashMap or ConcurrentHashMap(HashTable), depending on your specific requirements.
// we only add String->Double, but since you want to add "any type",
// we declare Map<Object, Object>
HashMap<Object, Object> map= new HashMap<>();
map.put("Zara", new Double(3434.34));
map.put("Mahnaz", new Double(123.22));
String[] names = map.keys();
while(names.hasMoreElements()) {
str = (String) names.nextElement();
System.out.println(str + ": " + map.get(str));
}
So, all objects in java have a class associated with them. Even raw Objects have a class: The Object class! You won't be able to create an object without a class because all values need to have a type of some sort. But that's really not a huge problem. If you need an object that stores certain values, you can just create a class that has space for those values. There's really no situation where you would not be able to do this.
That being said, if you just want a way of mapping keys to values, I'd recommend looking into the Map data structure.
JavaScript classes are different from Java classes, JavaScript is not a class-based object-oriented language, an object in JS is used as a template to hold properties, but in Java classes could hold variables (properties) and functions, so to initialize an object in Java there has to be a class for that object, you can think of it as a blueprint of how the object will be initiated for example to create a class:
public class Example {
public String link = "https://stackoverflow.com/";
public void printLink() {
System.out.println(link); // Prints the string stored in link
}
public void openLink() {
// Some code to open the link in the browser
}
}
To initialize an object from the class you created call this in your main or somewhere where the code will run:
Example example = new Example();
example.printLink(); // Printed the link
example.openLink(); // Opened the link
example.link = "https://example-link.com/"; // Changed the link
Note that the Example class could be in a different file and the file name has to be the same as the class name, here it is (Example.java)
Anyway if you are looking for an equivelant for JavaScript classes HashMap or HashTable could be very close.
This question already has answers here:
What is an efficient way to implement a singleton pattern in Java? [closed]
(29 answers)
Closed 5 years ago.
When I learn guava,I found some code like this in com.google.common.hash.Hashing class:
public static HashFunction crc32c() {
return Crc32cHolder.CRC_32_C;
}
private static final class Crc32cHolder {
static final HashFunction CRC_32_C = new Crc32cHashFunction();
}
I want to know, why do not write like below, Is this merely the author's habit? or for other purpose?
public static HashFunction crc32c() {
return new Crc32cHashFunction()
}
Your alternative suggestion
public static HashFunction crc32c() {
return new Crc32cHashFunction()
}
would create a new Crc32cHashFunction instance each time crc32c() is called. If there is no specific need for a new instance to be returned by each call, it is more efficient to return the same instance in each call.
Using the static final variable
static final HashFunction CRC_32_C = new Crc32cHashFunction();
is one way to achieve a single instance.
As to why the HashFunction instance is a member of the nested class Crc32cHolder (as opposed to being a member of the outer class), the motivation is probably lazy evaluation - only at the first time the crc32c() method is called, the Crc32cHolder class would be initialized and the Crc32cHashFunction instance would be created. Thus, if that method is never called, the Crc32cHashFunction would never be created (assuming there is no other access to the Crc32cHolder class).
I am trying to create an array of a class within a class so that I can have multiple sets of the inner class. However because I cannot create an empty an array in Java, I was wonder what's the best way to set this up. I know I can just define an array that is bigger than I would ever use but I feel that kind of sloppy programming.
Here's the important part of the 2 classes:
public class xmldata {
String Barcode;
String First;
String Last;
String Phone;
String Email;
String md5sum;
String zipfile;
picture_data[] pics;
...
public class picture_data {
static String filename;
static String directory;
As you can see, I to have an array of picture_data in xmldata. I have seen some stuff using lists but the examples are different and I am not sure I understand how to apply it in my case.
Here's the code I used to try and populate the arrays.
xmldata data = new xmldata();
ResultSet pictures=db.query("select * from pictures where barcode=?",barcode);
int i = -1;
while (pictures.next()) {
++i;
data.pics[i].setdirectory(pictures.getString("path"));
data.pics[i].setfilename(pictures.getString("filename"));
}
Any suggestions would be appreciated.
Modern idiomatic Java doesn't use raw Arrays or Vector either, it uses type safe List implementations.
Also picture_data and xmldata are not idiomatic naming convention for classes in Java, it should be PictureData and XMLData. I would challenge the semantics of a class called PictureData or XMLData as well.
A correct solution would be something like
List<PictureData> list = new ArrayList<PictureData>();
Understanding how to work with the Collections framework in Java is a fundamental requirement to be productive. Type safe Lists are a core component to writing real Java code.
If your array's size is going to be dynamic, then use lists inside and an ArrayList precisely. This way, you don't have to take care about size because it's treated internally.
Create an object of picture_data and add it into a ArrayList of picture_data
Then convert that arraylist into an array
Convert ArrayList<String> to String[] array
http://www.java-tips.org/java-se-tips/java.lang/how-to-convert-an-arraylist-into-an-array.html
Best option would be to use lazy initialized ArrayList
public class Xmldata {
List<picture_data> pics;
public void addPics(picture_data data) {
if(pics == null) pics = new ArrayList<picture_data>();
pics.add(data);
}
}
Here the pics list will only be created if the picture_data type objects are added to the Xmldata class
Basic question from somebody coming from structured into object programming... hoping not to be too basic.
I want to have a large array of data that is been shared by different classes inside my application.
What's the best practice to do this?
Is this correct?
public class LargeData {
private static long[] myData;
private static final int MAX = 100000;
public LargeData() {
myData = new long[MAX];
// ... initialize
}
public long getData(int x) {
// ... do whatever and return a long
}
}
And if this is correct, how is the correct way to access this data from any of my classes? Should I make a
LargeData ld = new LargeData();
inside every single class that wants to access to myData?
Thank you and sorry for being too easy... :)
use a Singleton pattern for this.
Everytime you call
LargeData ld = new LargeData();
in your code, you will be effectively calling
myData = new long[MAX];
which is wrong.
What you can do is:
public class LargeData {
private static final int MAX = 100000;
public static long[] myData = new long[MAX];
}
and access it as LargeData.myData from anywhere.
initialize array immediately. with current implementation you won't be able to use static array until create object of LargeData.
Also if class just for holding array prevent its instantiation and extension by making it final and constructor as private.
public final class LargeData {
public static long[] myData = new long[100000];
private LargeData() { }
}
And get access as LargeData.myData
Assigning values to static variables from instance constructors is a bad idea without a null check - if you ever instantiate two objects from this class the second will cause you to lose all data stored in the array (you lose the reference to the old array when the second instantiation overwrites the static reference). With null check it is also a bad idea though, unless you really really really need the data in one instance sort of a "global variable" way. It is best to think of static references as global variables which can be either viewable by all (if they are public) or visible only from the class you define it in (private) or something in between (protected or package protected access). You pretty much want to avoid using them though in almost all cases and use the Singleton pattern instead of static variables inside classes. With the Singleton pattern you use instance variables and non-static getters to get to the data.
However I do not see given the things you wrote why you would need a singleton pattern for this particular problem - you just want to store data in an object and share that object around, right?
You can fix the posted code like this without static keywords and this allows multiple LargeData instances to be alive at once in your application:
public class LargeData {
private long[] myData; // instance variable to store the data
private static final int MAX = 100000; // max length
public LargeData() {
myData = new long[MAX];
}
public long[] getData() {
return myData;
}
}
Then you can use the data as:
LargeData ld = new LargeData();
long[] = ld.getData();
And you can use the reference stored in ld any way you like, you can pass it around your other classes, etc.
A better idea would be to not expose the array, rather create an API through which you use the stored data. For example:
public long getLong(int n) { return myData[n]; }
public void setLong(int n, long value) { myData[n] = value; }
Now if you don't want to pass around the reference to the LargeData instance stored in ld, you can use a static variable in LargeData to store the reference and a static getter which lets you access it from any other java code. If you need multiple LargeData instances to work with you can create a LargeDataRegistry class that encapsulate a Map where you would store each instantiated LargeData instance.
This question already has answers here:
How to return multiple objects from a Java method?
(25 answers)
Closed 9 years ago.
How to create a JAVA function with multiple outputs?
Something like:
private (ArrayList<Integer[]>, int indexes) sortObjects(ArrayList<Integer[]> arr) {
//...
}
Java's not like Python - no tuples. You have to create an Object and wrap all your outputs into it. Another solution might be a Collection of some sort, but I think the former means better encapsulation.
In some cases it is possible to use method arguments to handle result values. In your case, part of the result is a list (which may be updated destructively). So you could change your method-signature to the following form:
private int sortObjects(ArrayList<Integer[]> input, ArrayList<Integer[]> result) {
int res = 0;
for (Integer[] ints : input) {
if (condition(ints) {
result.add(calculatedValue);
res++
}
}
return res;
}
You cannot, you can either
Create a wrapper return object
Create multiple functions
Use an object as return value.
class SortedObjects { private ArrayList<Integer[]> _first; int _indexes; ...getter/setter/ctor... }
private SortedObjects sortObjects(ArrayList<Integer[]> arr) { ... }
You cannot.
The simple solution is to return an array of objects. A more robust solution is to create a class for holding the response, and use getters to get the individual values from the response object returned by your code.
You have to create a class which includes member variables for each piece of information you require, and return an object of that class.
Another approach is to use an Object which wraps the collection.
class SortableCollection {
final List<Integer[]> tables = ...
int indexes = -1;
public void sortObjects() {
// perform sort on tables.
indexes = ...
}
}
As it operates on a mutable object, there is no arguments or return values.