Array list object help (static error) - object

import java.util.Scanner;
import java.util.ArrayList;
public class fester
{
public static void main(String args[] )
{
ArrayList<BankAccount> ba = new ArrayList<BankAccount>();
ba.add(new BankAccount("hi", 4));
}
class BankAccount
{
private String name;
private double amount;
public BankAccount(String name, Double amount)
{
this.name = name;
this.amount = amount;
}
public String getName()
{
return this.name;
}
public double getAmount()
{
return this.amount;
}
}
}
I dont get problem. I tried to almost copy this
http://www.java2s.com/Code/Java/Collections-Data-Structure/Storeuserdefinedobjectsinarraylist.htm
and it works. I'm very lost, and I cant see the fundamental differences.

You constructed class BankAccount as nested inner class (which means that you need an object of the outer class in order to instantiate it).
Move it outside of fester and replace 4 with 4.0 it'll work:
class fester {
public static void main(String args[]) {
ArrayList<BankAccount> ba = new ArrayList<BankAccount>();
ba.add(new BankAccount("hi", 4.0));
}
}
class BankAccount {
private String name;
private double amount;
public BankAccount(String name, Double amount) {
this.name = name;
this.amount = amount;
}
public String getName() {
return this.name;
}
public double getAmount() {
return this.amount;
}
}
Comment: You should follow Java naming convention and rename fester to Fester (with a capital letter).

Related

Model mapper mapping Map<String,Object> to class which extends another generic class not working for list field

I am trying to create my custom configuration object from Map using model mapper. Everything gets mapped properly excepts the fields property which is coming fro Generic super class.
My target object is
public class ADParserConfig extends CustomParserConfig<ADParserConfigField> {
private String pattern;
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
}
This extends generic class CustomParserConfig
public class CustomParserConfig<T extends CustomParserConfigField> {
protected List<T> fields;
protected String timeStampField;
public List<T> getFields() {
return fields;
}
public void setFields(List<T> fields) {
this.fields = fields;
}
public String getTimeStampField() {
return timeStampField;
}
public void setTimeStampField(String timeStampField) {
this.timeStampField = timeStampField;
}
}
Where CustomParserConfigField is
public class CustomParserConfigField {
protected String name;
protected Integer index;
protected String type;
protected String format;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
I am trying to map Map using below function
ADParserConfig adParserConfig = getConfig(map,ADParserConfig.class);
public <T extends CustomParserConfig> T getConfig(Map<String,Object> configObject, Class<T> classType){
ModelMapper modelMapper = new ModelMapper();
return modelMapper.map(configObject,classType);
}
Everything excepts fields gets mapped properly for the below map.
{fields=[{name=timeStamp, type=timestamp, format=dd/mm/yyyy HH:MM:SS a}, {name=logName, type=string}], pattern=(?<timeStamp>\d{2}\/\d{2}\/\d{4}\s\d{2}:\d{2}:\d{2}\s[AMPMampm]{2})?\s(LogName=(?<logName>[\w\s\W]+))?\sSourceName=(?<sourceName>[\w\s\W]+)\sEventCode=(?<eventCode>[0-9]*), timeStampField=timestamp}
Please help. Why is issue happens only for fields object ? Do I need to specify something else in mapper configurations ?
It looks like a bug and it had been fixed by #370

issues with parcelable extension: getting unmarshalling unknown type code exception

long story short, I have one settlementItemeBase class as my father and two children. I want to make the father class parcelable so as extension happens, my two child classes be parcelable as well. I don't exactly know what I'm doing right or wrong. I searched little bit but nothing helped me.
here are my classes:
SettlementItemBase:
public class SettlementItemBase implements Parcelable{
public SettlementItemBase(){}
protected SettlementItemBase(Parcel in) {
}
public static final Creator<SettlementItemBase> CREATOR = new Creator<SettlementItemBase>() {
#Override
public SettlementItemBase createFromParcel(Parcel in) {
return new SettlementItemBase(in);
}
#Override
public SettlementItemBase[] newArray(int size) {
return new SettlementItemBase[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
}
}
first child class:
public class FirstClass extends SettlementItemBase {
private int id;
private int cardId;
private String cardNumber;
private String expDate;
private String currency;
private String url;
public FirstClass(){
id = 0;
cardId = 0;
cardNumber = "";
expDate = "";
currency = "";
url = "";
}
protected FirstClass(Parcel in) {
super(in);
id = in.readInt();
cardId = in.readInt();
cardNumber = in.readString();
expDate = in.readString();
currency = in.readString();
url = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeInt(cardId);
dest.writeString(cardNumber);
dest.writeString(expDate);
dest.writeString(currency);
dest.writeString(url);
}
public int getId() {
return id;
}
public int getCardId() {
return cardId;
}
public String getCardNumber() {
return cardNumber;
}
public String getExpDate() {
return expDate;
}
public String getCurrency() {
return currency;
}
public String getUrl() {
return url;
}
}
second child class:
public class SecondClass extends SettlementItemBase{
private int id;
private String currency;
private String accountNumber;
private String ibanNumber;
public SecondClass(int id, String currency,
String accountNumber, String ibanNumber){
this.id = id;
this.currency = currency;
this.accountNumber = accountNumber;
this.ibanNumber = ibanNumber;
}
protected SecondClass(Parcel in){
super(in);
id = in.readInt();
currency = in.readString();
accountNumber = in.readString();
ibanNumber = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(currency);
dest.writeString(accountNumber);
dest.writeString(ibanNumber);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCurrency() {
return currency;
}
public String getAccountNumber() {
return accountNumber;
}
public String getIbanNumber() {
return ibanNumber;
}
}
I'm passing and getting an ArrayList of both child class' items with intent putParcelableArrayListExtra and getParcelableArrayListExtra methods and get the following error:
Parcel android.os.Parcel#2d0fde33: Unmarshalling unknown type code 3276849 at offset 172
any help would be appreciated 3>
well I'm posting this for those who may run into the same problem as me.
the problem was solved after adding the Creator statement to the child classes.
for one of the child classes it would be like:
public static final Creator<FirstClass> CREATOR = new Creator<FirstClass>() {
#Override
public FirstClass createFromParcel(Parcel in) {
return new FirstClass(in);
}
#Override
public FirstClass[] newArray(int size) {
return new FirstClass[size];
}
};
hope this helps. 3>

Field attribute is coming as null while unmarshalling an xml file

Hi I am trying to convert an xml file into Java Objects using JAXB and I am very new to java. I have created the pojo classes and added some annotations but I am not sure whether they are right? I have spent hours in google but couldn't find what is wrong.
This is my xml :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<question id="1">
<answers>
<answername>java is a programming language</answername>
<id>101</id>
<postedby>ravi</postedby>
</answers>
<answers>
<answername>java is a platform</answername>
<id>102</id>
<postedby>john</postedby>
</answers>
<questionname>What is java?</questionname>
<marks set=50>
<longAnswer set=45/>
<shortAnswer set=30/>
</marks>
</question>
Pojo classes:
#XmlRootElement(name="question")
public class Question {
private int id;
private String questionname;
private List<Answer> answers;
private List<Marks> marks;
public Question() {}
public Question(int id, String questionname, List<Answer> answers, List<Marks> marks) {
super();
this.id = id;
this.questionname = questionname;
this.answers = answers;
this.marks = marks;
}
#XmlElement(name="marks")
public List<Marks> getMarks() {
return marks;
}
public void setMarks(List<Marks> marks) {
this.marks = marks;
}
#XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement
public String getQuestionname() {
return questionname;
}
public void setQuestionname(String questionname) {
this.questionname = questionname;
}
#XmlElement
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers(List<Answer> answers) {
this.answers = answers;
}
}
public class Answer {
private int id;
private String answername;
private String postedby;
public Answer() {}
public Answer(int id, String answername, String postedby) {
super();
this.id = id;
this.answername = answername;
this.postedby = postedby;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAnswername() {
return answername;
}
public void setAnswername(String answername) {
this.answername = answername;
}
public String getPostedby() {
return postedby;
}
public void setPostedby(String postedby) {
this.postedby = postedby;
}
}
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
public class Marks {
private LongAnswer longAnswer ;
private ShortAnswer shortAnswer;
private String set;
#XmlAttribute
public String getSet() {
return set;
}
public void setSet(String set) {
this.set = set;
}
#XmlElement(name="longAnswer")
public LongAnswer getLongAnswer() {
return longAnswer;
}
public void setLongAnswer(LongAnswer longAnswer) {
this.longAnswer = longAnswer;
}
#XmlElement(name="shortAnswer")
public ShortAnswer getShortAnswer() {
return shortAnswer;
}
public void setShortAnswer(ShortAnswer shortAnswer) {
this.shortAnswer = shortAnswer;
}
}
public class LongAnswer {
private String set;
public String getSet() {
return set;
}
public void setSet(String set) {
this.set = set;
}
public class ShortAnswer {
private String set;
public String getSet() {
return set;
}
public void setSet(String set) {
this.set = set;
}
}
Can anyone tell me how to annotate the 'marks' model class and how to set 'longAnswer' and 'shortAnswer' field. Because i am getting null values for them.
You should annotate your set properties with #XmlAttribute. Otherwise it looks quite fine.
What you could also do is create an XML Schema for you XML and compile it.

Using a string to specify an object in Java

I have a Combo Bx (Dropdown box) with an index range of 0-20. If there anyways I can use that index to specify which object I want data from? All of the objects use the same naming convention obj0, obj1, obj2, etc. Basically something like this...
public abstract class Person {
private String name;
private String title;
private String email;
private String job;
public Person(String name, String title, String email, String job){
this.name = name;
this.title = title;
this.email = email;
this.job = job;
}
//Getters and Setters
}
public class main extends javax.swing.JFrame {
...misc code...
private void btn_startActionPerformed(java.awt.event.ActionEvent evt) {
Person obj0 = new Person("Jon Doe",
"Program Coordinator",
"jon.doe#test.com",
"Faculty");
Person obj1 = ...
...
Person obj20 = ...
/*
Onclick it uses the index of the current index in the combobox (dropdown)
to specify which object to get the data from.
*/
private void btn_GetActionPerformed(java.awt.event.ActionEvent evt) {
//Uses the obj naming convention plus the index
string foo = "obj" + toString(combobox_Name.getSelectedIndex());
//Fills the textbox using the above string and the getName method
txtbox_username.setText(ToObject(foo).getName);
}
I have created a basic design of what I think you want:
This code creates 20 objects, adds them to a combobox and uses their predefined name when selected to change a textfield.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
class ObjExample {
String name;
public ObjExample(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
}
public class Main extends JFrame implements ActionListener {
JComboBox jcb = new JComboBox();
JTextField jtf = new JTextField("Text Field");
public Main() {
setSize(200, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
for (int i = 0; i <= 20; i++) {
jcb.addItem(new ObjExample(Integer.toString(i)));
}
jcb.addActionListener(this);
add(jcb);
add(jtf);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jcb) {
ObjExample obj = (ObjExample) jcb.getSelectedItem();
jtf.setText(obj.toString());
}
}
}

#XmlAttribute/#XmlValue need to reference a Java type that maps to text in XML

how to pick the value of an attribute 'name' which is a PriceEventName class type in the below case, FYI if i put #XmlAttribute above it this is turn out to an exception "an error #XmlAttribute/#XmlValue need to reference a Java type that maps to text in XML"
I looking heavily on the internet but I didn't find something similar to my case
PriceEvent class
package somepackage
import ...
import
#XmlAccessorType(XmlAccessType.FIELD)
public class PriceEvent {
#XmlElement(name="Message",namespace="someValue")
private String color;
private PriceEventName name;// this is an attribute
.
.
}
PriceEventName class
Imports ...
public class PriceEventName {
public static final int PRICEUPDATE_TYPE = 0;
public static final PriceEventName PRICEUPDATE = new PriceEventName(PRICEUPDATE_TYPE, "X-mas");
private static java.util.Hashtable _memberTable = init();
private static java.util.Hashtable init() {
Hashtable members = new Hashtable();
members.put("X-mas", PRICEUPDATE);
return members;
}
private final int type;
private java.lang.String stringValue = null;
public PriceEventName(final int type, final java.lang.String value) {
this.type = type;
this.stringValue = value;
}
public static PriceEventName valueOf(final java.lang.String string) {
java.lang.Object obj = null;
if (string != null) {
obj = _memberTable.get(string);
}
if (obj == null) {
String err = "" + string + " is not a valid PriceEventName";
throw new IllegalArgumentException(err);
}
return (PriceEventName) obj;
}
}
This is how you declare the field as an attribute with an adapter:
#XmlJavaTypeAdapter(PenAdapter.class)
#XmlAttribute
protected PriceEventName name;
public PriceEventName getName() { return name; }
public void setName(PriceEventName value) { this.name = value; }
Add you'll need to add a getter to PriceEventName:
public String getStringValue(){ return stringValue; }
And here is the adapter class:
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class PenAdapter extends XmlAdapter<String,PriceEventName> {
public PriceEventName unmarshal(String v) throws Exception {
return PriceEventName.valueOf( v );
}
public String marshal(PriceEventName v) throws Exception {
return v.getStringValue();
}
}

Resources