Structured data in java [duplicate] - java

This question already has answers here:
Struct like objects in Java
(20 answers)
Closed 9 years ago.
In C I would create a data structure as below:
struct file_data_format
{
char name[8][20];
float amp[8];
int filter[8];
};
extern struct file_data_format f_data;
Then I could read or write this whole structure to a file or memory location.
How would I do this in a class in java?

You should read basics of Java before asking. Structure in C can be written as Class in Java.
public class FileDataFormat implements Serializable {
String[][] name = new String[8][20];
float[] amp = new float[8];
int[] filter = new int[8];
public FileDataFormat() {
}
public void setName(String[][] name) {
this.name = name;
}
public String[][] getName() {
return this.name;
}
// next getters and setters
}
I pretty recommend OOP(encapsulation, polymorphism, inheritance).

If you want to achieve a similar effect, you can do the following.
Unfortunately, you don't have so much control over how it's represented in memory as you do in c
public class file_data_format
{
public char name[8][20];
public float amp[8];
public int filter[8];
}
...
public static void main()
{
file_data_format fdf = new file_data_format();
fdf.name = charArrayIGotFromSomewhere
}

public class FileDataFormat {
private String name;
private float amp;
private int filter;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getAmp() {
return amp;
}
public void setAmp(float amp) {
this.amp = amp;
}
public int getFilter() {
return filter;
}
public void setFilter(int filter) {
this.filter = filter;
}
}

The equivalent of a struct in Java is a JavaBean, as other answers has shown you.
From Wikipedia, a JavaBean :
is serializable
has a 0-argument constructor
allows access to properties using getter and setter methods.
To write and read it from file or memory, it is not as simple as in C. You would typically use Java Object serialization to write/read your objects to an ObjectInputStream/ObjectOutputStream, that could be attached to a file or a byte array.

Related

Enums in Java VS Enums in C# [duplicate]

This question already has answers here:
C# vs Java Enum (for those new to C#)
(13 answers)
Is it possible to add custom properties to c# enum object?
(2 answers)
Closed 2 years ago.
I have a very basic question. In Java, it is possible to point attributes and variables to Enums, such as:
public enum DayTime{
Morning("Morning"),
Afternoon("Afternoon"),
Night("Night");
private string description;
Daytime(string description){
this.description = description;
}
public string getDescription(){
return description;
}
}
Is it possible to apply the same concept to C#? I am trying to get modular descriptions to products, whereas their name, contents and characteristics would be shown in a string of text, and Enums looked like the best alternative to modify this text according to which characteristic is selected.
C# enums are very basic compared to Java enums. If you want to simulate the same kind of behavior you need to use a class with an inner enum:
using System.Collections.Generic;
public sealed class DayTime
{
public static readonly DayTime Morning = new DayTime("Morning", InnerEnum.Morning);
public static readonly DayTime Afternoon = new DayTime("Afternoon", InnerEnum.Afternoon);
public static readonly DayTime Night = new DayTime("Night", InnerEnum.Night);
private static readonly List<DayTime> valueList = new List<DayTime>();
static DayTime()
{
valueList.Add(Morning);
valueList.Add(Afternoon);
valueList.Add(Night);
}
//the inner enum needs to be public for use in 'switch' blocks:
public enum InnerEnum
{
Morning,
Afternoon,
Night
}
public readonly InnerEnum innerEnumValue;
private readonly string nameValue;
private readonly int ordinalValue;
private static int nextOrdinal = 0;
private string description;
internal DayTime(string name, InnerEnum innerEnum)
{
this.description = name;
nameValue = name;
ordinalValue = nextOrdinal++;
innerEnumValue = innerEnum;
}
public string Description
{
get
{
return description;
}
}
//the following methods reproduce Java built-in enum functionality:
public static DayTime[] values()
{
return valueList.ToArray();
}
public int ordinal()
{
return ordinalValue;
}
public override string ToString()
{
return nameValue;
}
public static DayTime valueOf(string name)
{
foreach (DayTime enumInstance in DayTime.valueList)
{
if (enumInstance.nameValue == name)
{
return enumInstance;
}
}
throw new System.ArgumentException(name);
}
}
Given this complexity, it may be best to rewrite your logic in a way that's more natural for C# without using enums.

Create tasks[] an array of task

My current problem is that I am assigned to created a program that should within the private fields assign tasks[] an array of task. Then within the constructor, that creates the task[] array, giving it the capacity of INITIAL_CAPAITY, and setting numTasks to zero.
I am new and confused on I can tackle this problem
I have tried declaring it within the constructor but there has been no luck.
Task.java
public class Task {
private String name;
private int priority;
private int estMinsToComplete;
public Task(String name, int priority, int estMinsToComplete) {
this.name=name;
this.priority=priority;
this.estMinsToComplete = estMinsToComplete;
}
public String getName() {
return name;
}
public int getPriority() {
return priority;
}
public int getEstMinsToComplete() {
return estMinsToComplete;
}
public void setName(String name) {
this.name = name;
}
public void setEstMinsToComplete(int newestMinsToComplete) {
this.estMinsToComplete = newestMinsToComplete;
}
public String toString() {
return name+","+priority+","+estMinsToComplete;
}
public void increasePriority(int amount) {
if(amount>0) {
this.priority+=amount;
}
}
public void decreasePriority(int amount) {
if (amount>priority) {
this.priority=0;
}
else {
this.priority-=amount;
}
}
}
HoneyDoList.java
public class HoneyDoList extends Task{
private String[] tasks;
//this issue to my knowledge is the line of code above this
private int numTasks;
private int INITIAL_CAPACITY = 5;
public HoneyDoList(String tasks, int numTasks, int INITIAL_CAPACITY,int estMinsToComplete, String name,int priority) {
super(name,priority,estMinsToComplete);
numTasks = 0;
tasks = new String[]{name,priority,estMinsToComplete};
//as well as here^^^^^^^^
}
My expected result is to be able to print out the list through honeydo class. I need to manipulate the code a bit more after adding a few other methods.
Your problem is that your constructor parameter tasks has the same name as that field of your class.
So you assign to the method parameter in your constructor, not to the field. And luckily those two different "tasks" entities have different types, otherwise you would not even notice that something is wrong.
Solution: use
this.tasks = new String...
within the body of the constructor!
And the real answer: you have to pay a lot attention to such subtle details. And by using different names for different things you avoid a whole class of issues!
Also note: it sounds a bit strange that a class named Task contains a list of tasks, which are then strings. The overall design is a bit weird...

Loop over object setters java [duplicate]

This question already has answers here:
Invoking all setters within a class using reflection
(4 answers)
Closed 5 years ago.
I have a POJO object and a collection of appropriate data.
import java.util.ArrayList;
import java.util.List;
public class TestPojo {
private String name;
private String number;
private String id;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public static void main(String[] args) {
TestPojo test = new TestPojo();
List<String> sampleData = new ArrayList<>();
sampleData.add("Bob");
sampleData.add("641-613-623");
sampleData.add("id-1451");
sampleData.add("Male");
test.setName(sampleData.get(0));
test.setNumber(sampleData.get(1));
test.setId(sampleData.get(2));
test.setSex(sampleData.get(3));
}
}
My question is how can i fill my POJO object with data in a loop? Is it posible to iterate all object setters and set data from List in appropriate places? I know that reflection can help in this case.
Here is an simple example to call setters via reflection (which needs to be adjusted):
[if this is a good approach, is another question. But to answer your question:]
public static void main(String[] args) throws Exception
{
//this is only to demonstrate java reflection:
Method[] publicMethods = TestPojo.class.getMethods(); //get all public methods
TestPojo testObj = TestPojo.class.newInstance(); //when you have a default ctor (otherwise get constructors here)
for (Method aMethod : publicMethods) //iterate over methods
{
//check name and parameter-count (mabye needs some more checks...paramter types can also be checked...)
if (aMethod.getName().startsWith("set") && aMethod.getParameterCount() == 1)
{
Object[] parms = new Object[]{"test"}; //only one parm (can be multiple params)
aMethod.invoke(testObj, parms); //call setter-method here
}
}
}
You can also save all setter-methods in an list/set for later re-use...
But as others already said, you have to be careful by doing so (using reflection)!
Cheers!
You can't easily - and you shouldn't.
You see, your POJO class offers some setters. All of them have a distinct meaning. Your first mistake is that all of these fields are strings in your model:
gender is not a string. It would rather be an enum.
"number" is not a string. It should rather be int/long/double (whatever the idea behind that property is)
In other words: you premise that "input" data is represented as array/list is already flawed.
The code you have written provides almost no helpful abstractions. So - instead of worrying how to call these setter methods in some loop context - you should rather step back and improve your model.
And hint: if this is really about populating POJO objects from string input - then get your string into JSON format, and use tools such as gson or jackson to do that (reflection based) mapping for you.
"Iterating over methods" seems pretty much of a wrong idea in OO programming. You could simply add a constructor to your class setting all of your attributes, and then just call that constructor in a loop as desired to create new objects with data you desire.
In your class define:
public TestPojo(String name, String number, String id, String sex){
this.name = name;
this.number = number;
this.id = id;
this.sex = sex;
}
Also using a List makes no much sense here. I'd recommend using a HashMap to then iterate over it in a for loop making proper calls of the above constructor.

How to create get and set methods for parameters in a class? [duplicate]

This question already has answers here:
How do getters and setters work?
(6 answers)
Closed 7 years ago.
I have a class I created.
public class mailCustomer {
public static void main(String[] args) {
String Name;
int Id;
String Address;
Boolean IsPack;
}
}
I need to creat get and set methods for my parametrs, Name, Id,Address, IsPack.
how do I do that, and where do I write them? after the "main" method? in the "main" method?
Firstly, you need to declare the variables at the class level so that they can be used from anywhere within the class. Then after that you simply create a set and get method for each variable, like so
public class MailCustomer {
String name;
int id;
String address;
boolean isPack;
public static void main(String[] args) {
}
public void setName(String name) {
this.name = name;
}
public void setId(int id) {
this.id = id;
}
public void setAddress(String address) {
this.address = address;
}
public void setIsPack(boolean isPack) {
this.isPack = ispack;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public String getAddress() {
return address;
}
public boolean getIsPack() {
return isPack;
}
}
It also appears that you have your naming conventions a little mixed up. In java, class names are capitalized, whereas variable and method names are camelCased
First, delete the main method from there. You are creating a class called mailCustomer that will create you object type of mailCustomer.
For this, you need three things: attributes (you have them there), a constructor and get/set methods. I will show you with a example, and you can guide from there. My class will be 'Rabbit' and it will have:
Attributes
-String eyes: Eye colour.
-String race: Where is it from.
Constructor
It will have one constructor, that will use both parameters.
Methods
It will have two getters and two setters, both for each attribute.
Here's my code for this class:
public class Rabbit{
//Attributes
private String eyes;
private String race;
//Constructor
public Rabbit(String colour, String where){
this.eyes = colour;
this.race = where;
}
//Methods get/set
public String getEyes(){
return this.eyes;
}
public String getRace(){
return this.race;
}
public void setEyes(String colour){
this.eyes = colour;
}
public void setRace(String where){
this.race = where;
}
}
As you can see, you will use get methods to return an specific attribute from the class; and set methods will be used if you want to change one of the attributes from a created object (in my case, from a created 'Rabbit').
Later, if you want to make use of this class, you will create your Main class, into the same package where 'Rabbit' class is created.
package rabbit;
public static void main(String[] args){
Rabbit George = new Rabbit("brown","spanish");
}
Now try to do this with your class. I hope it helped you!
public static void main(String[] args) {
String Name;
int Id;
String Address;
Boolean IsPack;
}
You can't create getters and setters for these, since they are not created in your class, but locally in your main method. What you want is:
public class MyClass{
String Name;
int Id;
String Address;
Boolean IsPack;
// getter for Name
public String getName(){
return this.Name;
}
// setter for Name
public void setName(String name){
this.Name = name;
}
public static void main(String[] args) {
}
}
For these you'll be able to create getters and setters.
It's (most likely) best to declare them private, though.
Also: following naming conventions could help other people easier read your code. Name (with capital N) is more suited as name of a class, while name (lowercase n) is the name of a variable.
As already said it seems that you are not familiar with Object Oriented Programming. It does not care. I just want to say that you can save a lot of time and improve your classes readability using lombok to automatically generate your getters and setters using annotations. You can find an example here : LOMBOK

Sort Array of Objects by Objects' Property [duplicate]

This question already has answers here:
How do I use Comparator to define a custom sort order?
(9 answers)
Closed 9 years ago.
I know there are a lot of questions like this, and I have been reading a lot but I really can't figure it out. I have a user defined object, Team, which has the properties team name (String), batAvg (Double) and slugAvg (Double). I want to arrange, and print the teams in order of descending batAvg, then in order of descending slugAvg. I have an array of all the teams, teamArray (Team[]). What is the best way to go about sorting this array by the teams batting and slugging average. I've tried a bunch of stuff, but none of it seems to work.
Pls check the following code,
import java.util.Arrays;
import java.util.Comparator;
public class Team {
private String name;
private double batAvg;
private double slugAvg;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBatAvg() {
return batAvg;
}
public void setBatAvg(double batAvg) {
this.batAvg = batAvg;
}
public double getSlugAvg() {
return slugAvg;
}
public void setSlugAvg(double slugAvg) {
this.slugAvg = slugAvg;
}
public static void main(String[] argv){
Team[] teams = new Team[2]; //TODO, for testing..
Arrays.sort(teams, new TeamComparator()); //This line will sort the array teams
}
}
class TeamComparator implements Comparator<Team>{
#Override
public int compare(Team o1, Team o2) {
if (o1.getSlugAvg()==o2.getSlugAvg()){
return 0;
}
return o1.getSlugAvg()>o2.getSlugAvg()?-1:1;
}
}

Categories

Resources