I want to add the name of array in the class to jList as below.
How can it be?
this is the method in display class
public void dataToLocal(List<XDataObject> data, XServiceType xst, XServiceOperation operation) {
if(operation.getName().equals(SNOWTAMSubscriberServiceInterface.OP_PUBLISSNOWTAM)) {
SNOWTAMPublication snowtamPublication =
(SNOWTAMPublication)data.get(0).getValue(); //This read an array with 5 values.
SNOWTAM snowtam = snowtamPublication.getSNOWTAM()[0]; //This read read the array and its contents.
jList1.add((Component) Arrays.asList((snowtamPublication.getSNOWTAM()[0]).toString())); //Here I want to add the name of Array to be as below
}
}
This is SNOWTAMPublication which is only get and set methods for array.
protected SNOWTAM[] snowtam;
public SNOWTAM[] getSNOWTAM() {
if(snowtam == null)
{
snowtam = new SNOWTAM[0];
}
return snowtam;
}
public void setSNOWTAM(SNOWTAM[] _value) {
this.snowtam = _value;
}
The picture
You could try:
<instance>.getClass().getSimpleName()
Related
I've defined a arrayList as following
List<List<RiskyPersons>> dataArray = new ArrayList<>();
Here is RiskyPersons Class
public class RiskyPersons {
private SA3Tenant sa3tenant;
private int NumberofPersonInCategory;
public RiskyPersons(){
}
public RiskyPersons(SA3Tenant sa3tenant, int NumberofPersonInCategory) {
this.sa3tenant = sa3tenant;
this.NumberofPersonInCategory = NumberofPersonInCategory;
}
}
Then I've successfully added data and saved in dataArray ArrayList.
Following output is showing the saved ArrayList using SOP(dataArray);
[[RiskyPersons{sa3tenant=Homeless.SA3Tenant#3a7cc6b0, NumberofPersonInCategory=99}]]
I want to read this dataArray ArrayList and display values separately. How do I access "NumberofPersonInCategory" value?
From Java-8 and above one can use stream:
dataArray.stream()
.flatMap(List::stream)
.map(RiskyPersons::NumberofPersonInCategory)
.forEach(System.out::println)
I hope this will help you !
public class RiskyPersons {
private SA3Tenant sa3tenant;
private int NumberofPersonInCategory;
public int getNumberofPersonInCategory() {
return NumberofPersonInCategory;
}
public RiskyPersons(){
}
public RiskyPersons(SA3Tenant sa3tenant, int NumberofPersonInCategory) {
this.sa3tenant = sa3tenant;
this.NumberofPersonInCategory = NumberofPersonInCategory;
}
}
List<Integer> values = dataArray.parallelStream().flatMap(Collection::stream).map(RiskyPersons::getNumberofPersonInCategory)
.collect(Collectors.toCollection(ArrayList::new));
You'll need to iterate it twice as
for (List<RiskyPersons> rp : dataArray) {
for (RiskyPersons o : rp) {
System.out.println(o.NumberofPersonInCategory); // unrelated : but its bad naming convention
}
}
I have two objects(which contain of list of objects) of same class.I need to find whether both are same or not.
Consider below example:
class Device {
String deviceName;
String devLocation;
String devType;
String devID;
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getDevLocation() {
return devLocation;
}
public void setDevLocation(String devLocation) {
this.devLocation = devLocation;
}
public String getDevType() {
return devType;
}
public void setDevType(String devType) {
this.devType = devType;
}
public String getDevId() {
return devID;
}
public void setDevId(String devId) {
this.devID = devId;
}
}
class DevList {
List<Device> deviceList;
public List<Device> getDevices() {
return deviceList;
}
public void setDevices(List<Device> deviceList) {
this.deviceList = deviceList;
}
}
Need to compare two objects of DevList class.
Will get a new DevList object for every regular interval of time.
Every time i need to verify current object with previous object and update DB if there is any difference else ignore.
The list(deviceList) in current and previous objects might not be in same order.
for example:
Consider below two objects which are in Json format(Please ignore json format errors).
Object 1:
{
"devList":[
{
"deviceName":"ABC",
"devLocation":"India",
"devType":"Router",
"devID":"1111"
},
{
"deviceName":"XYZ",
"devLocation":"India",
"devType":"Router",
"devID":"2222"
}
]
}
Object 2:
{
"devList":[
{
"deviceName":"XYZ",
"devLocation":"India",
"devType":"Router",
"devID":"2222"
},
{
"deviceName":"ABC",
"devLocation":"India",
"devType":"Router",
"devID":"1111"
}
]
}
We can do it by iterating lists in both objects by checking devID. But complexity would be M*N.
Is there any other way?
You could override equals in Device to compare each Device object.
Something similar
class Device {
...
...
//your getter and setter
public boolean equals (Object obj)
{
if (Device.class != obj.getClass()) {
return false;
}
if (obj instanceof Device) {
return (deviceName.equals(((Device) obj).deviceName) &&
devLocation.equals(((Device) obj).devLocation) &&
devType.equals(((Device) obj).devType) &&
devID.equals(((Device) obj).devID));
}
return false;
}
}
Now, call removeAll, which will remove same object list from List1
List1.equals(List2);
So, if both list has same object list, then List1 would be empty.
Step 1: First override equal method in Device Class
Step 2: override the equal() in your DevList class with
with below logic
1. use one Set collection
2. add object into it from 1st Object's list
3. check size() of set
3. add object from 2nd Object's list
5. check size() of set every time you add from 2nd list
6. if more than the size of one list it is not equal(As Set will not keep duplicate value)
The code looks like this.
public class Album {
public String currentTitle;
public HashMap<String, List<Music>> albumList = new HashMap<String, List<Music>>();
//setting the album's title
public Album(String albumTitle) {
this.currentTitle = albumTitle; //represents object's name
albumList.put(currentTitle, null);
}
//add music to album
public void addMusicToThis(Music music) {
//only if value is empty
if(albumList.get(currentTitle) == null) {
albumList.put(currentTitle, new ArrayList<Music>());
}
albumList.get(currentTitle).add(music);
}
public void printMusicList() {
}
}
and I want to print all values for the specific album, like
Album album = new Album("Test1");
Album album2 = new Album("Test2");
album.addMusicToThis(something); //this code works fine
album2.addMusicToThis(something2);
album.printMusicList(); //maybe "something"
album2.printMusicList(); //maybe "something2"
but the hashMap's values are all set to List, and I can't find the way to print the musics out.
And assume that music's name is all set.
You just get the list for a particular string, and iterate it
for(Music m : albumList.get(this.currentTitle)) {
System.out.println(m.getName());
}
It's not really clear why you're using a Hashmap, though. Your key can never change.
You must iterate over the obtained list and print the individual entries
In Java 8 you can,
albumList.get(currentTitle).forEach((music) -> System.out.println(musice.getRequiredDetails)})
You can call albumList.entrySet() which is actually iterable, traverse it and print it however you like
I think you should add the albumTitle as an argument of the printMusicList function.
For example
public void printMusicList(String albumTitle) {
List<Music> musics = albumList.get(albumTitle);
for (Music music : musics) {
System.out.println(music);
}
}
or if you want to print it all
public void printMusicList() {
Set<String> keys = albumList.keySet();
for (String key : keys) {
List<Music> musics = albumList.get(key);
for (Music music : musics) {
System.out.println(music);
}
}
}
Below is the response i am getting from the server,
{
"section_id": "[24,1,5,2]"
}
and I am using GSON library
public class SectionModel {
#SerializedName("section_id")
private String mSectionId;
public String getmSectionId() {
return mSectionId;
}
public void setmProgramName(String mSectionId) {
this.mSectionId = mSectionId;
}
}
I am able to get the value "[2,18,25,26]" and store it in a String.
Now how am I supposed to get those values from String and store in an Integer arraylist.
Try this method in your code:
public ArrayList<Integer> returnArrayList(String parsetest){
ArrayList<Integer> integerArrayList= new ArrayList<>();
parsetest=parsetest.replace("[", "");
parsetest=parsetest.replace("]", "");
String[] list = parsetest.split(",");
for (String item : list) {
integerArrayList.add(Integer.valueOf(item));
}
return integerArrayList;
}
Feel free to ask any doubt in the method.
I'm writing a messaging system to queue actions for my program to execute. I need to be able to pass various objects by the messages. I currently have a Msg object that accepts (Action enum, Data<?>...object). The Data object is intended to be a wrapper for any object I might pass.
Currently the Data object uses this code, with generics:
public class Data<T> {
private T data;
public Data(T data){
this.data = data;
}
public T getData(){
return data;
}
}
The Msg object takes Data<?>... type, so Msg has a Data<?>[] field.
If getData() is called on a Data<?> object, it returns the Object type. Obviously not ideal.
I need to be able to pass, say, Image objects as well as String objects. I'm certain there's a better way of passing arbitrary data.
The reason you're having trouble is that you're trying to get the static typing system of Java to do something that it can't. Once you convert from a Data<T> to a Data<?>, whatever T was is effectively lost. There's no clean way to get it back.
The quickest way to get it to work (from what you have right now) is to start throwing casts everywhere, like this:
Data<?> d = new Data("Hello");
String contents = (String)d.getData();
This is kind of a terrible idea, so let's go back to the drawing board.
If (ideally), you have all of the types you could ever need ahead of time (i.e. every Data is either a String or an Image or an Integer), then you can pretty easily (though it's a bit tedious) define a Sum type (aka a union if you're coming from C) of the different types of data you'll have to handle. As a class invariant, we assume that exactly one of the fields is non-null, and the rest are null. For this example I'll assume it can be either a String, an Image, or an Integer, but it's fairly simple to add or remove types from Data as necessary.
public class Data {
private Image imgData;
private String stringData;
private Integer intData;
public Data(Image img) {
this.imgData = img;
}
public Data(String stringData) {
this.stringData = stringData;
}
public Data(Integer intData) {
this.intData = intData;
}
public boolean isImage() {
return imageData != null;
}
public boolean isInteger() {
return intData != null;
}
public boolean isString() {
return stringData != null;
}
public Image asImage() {
if(! isImage()) throw new RuntimeException();
return imgData;
}
public Image asString() {
if(! isString()) throw new RuntimeException();
return stringData;
}
public Image asInt() {
if(! isInt()) throw new RuntimeException();
return intData;
}
}
One necessary side effect is that we cannot wrap null without causing exceptional behavior. Is this is desired, it isn't too difficult to modify the class to allow for it.
With this Data class, it's pretty easy to do if-else logic to parse it.
Data d = ....... //Get a data from somewhere
if(d.isImage()) {
Image img = d.asImage();
//...
} else if (d.isString()) {
String string = d.asString();
//...
} else if (d.isInteger()) {
Integer i = d.asInt();
//...
} else {
throw new RuntimeException("Illegal data " + d + " received");
}
If you call getData().getClass() you will get the class or type that was passed, which doesn't seem to me to be the same as an Object. You might not know what you are getting, but you can either find out or define a common interface for everything you might pass. You could for example, call toString() or getClass() on anything passed. Your question is that you are passing any conceivable object, so my question is what are you going to do with it? If you are going to serialize it into a database you don't need know anything about what type it is, otherwise you can test it or call a common interface.
public class PlayData {
class Msg {
private List<Data<?>> message = new ArrayList<Data<?>>();
public void addData(Data<?> datum) { message.add(datum); }
public void printTypes() { for ( Data<?> datum: message ) { System.out.println(datum.getData().getClass()); } }
}
class Data<T> {
private T value;
public Data(T value) { this.value = value; }
public T getData() { return value; }
}
class Listener {
public void receive(Msg msg) { msg.printTypes(); }
}
class Sender {
private Listener listener;
public Sender(Listener listener) { this.listener = listener; }
public void send(Msg msg) { listener.receive(msg); }
}
class MyPacket {
int i;
public MyPacket(int i) { this.i = i; }
}
public static void main(String[] args) throws Exception { new PlayData().run(); }
public void run() throws Exception {
Sender sender = new Sender(new Listener());
Msg msg = new Msg();
msg.addData(new Data<String>("testing") );
msg.addData(new Data<MyPacket>(new MyPacket(42)) );
sender.send(msg);
}
}