How to add the value of all the objects? - java

Let's say we have a class SCORE. It has three objects s1,s2 and s3. SCORE has an attribute RUNS. How to add the runs of all the objects ? SCORE has an internal method int TOTALSCORE(). so when that method is called, it should return the total score .
How should i call that method ? Like s1.TOTALSCORE() ? Or any other way?

In rare cases the thing that you want could be reasonably, but normally the class is not aware of all it's elements. A total Score is for a Collection of Score elements, maybe a List or a Set.
So you would do:
class Score {
int value;
// ...
public static int totalScore(Collection<Score> scores){
int sum = 0;
for (Score s: scores){
sum += s.value;
}
return sum;
}
}
And outside you would have
List<Score> myBagForScores = new ArrayList<>();
Score e1 = new Score...
myBagForScores.add(e1);
// e2, e3 and so on
int sum = Score.totalScore(myBagForScores);
Hope that helps!

Here is a small Proof-Of-Concept:
public class Score {
private static ReferenceQueue<Score> scoreRefQueue = new ReferenceQueue<Score>();
private static List<WeakReference<Score>> runs = new ArrayList<WeakReference<Score>>();
static { // remove references to instances that are Garbage Collected
new Thread(new Runnable() {
#Override
public void run() {
while(true) try {
Object scoreRef = scoreRefQueue.remove(); // blocks until next reference is available
synchronized(runs) { // synch access with summing iterator
runs.remove(scoreRef);
}
} catch(Throwable t) {
// ignore
}
}
}).start();
}
/**
* The factory method
*/
public static Score getInstance() {
final Score score = new Score();
final WeakReference<Score> scoreRef = new WeakReference<Score>(score, scoreRefQueue);
synchronized(runs) {
runs.add(scoreRef);
}
return score;
}
private int total;
private Score() {
// prevent creating instances outside this class
}
/**
* The service method
*/
public static int totalScore() {
int totalScore = 0;
synchronized(runs) { // synch access with cleanup thread
for(WeakReference<Score> scoreRef : runs) {
final Score score = scoreRef.get();
if(score != null) {
totalScore += score.total;
}
}
}
return totalScore;
}
}
The idea is not to allow creating instances outside your factory method #getInstance(). The instances are tracked using WeakReferences to allow their Garbage Collection. The list is update by a service thread waiting on the reference queue. Hope this helps.

Related

Problems creating an object using a class and then putting it on a array

So I'm trying to do a User class and then trying to do an array for it
however every time I create a student it don't add to the array.
I tried to change names etc but its really a problem in code.
public class UsersList {
User student;
User[] studentList = new User[49];
public UsersList() {
}
public void createUser(int userNumber) {
String numberToString = String.valueOf(userNumber);
if (numberToString.length() == 9) {
for (int i = 0; i < 49; i++) {
if (studentList[i] == null) {
studentList[i] = new User(userNumber);
}
}
}
}
}
public class User {
public int userNumber;
private boolean isolation;
private String state;
public User(int number) {
userNumber = number;
isolation = false;
}
}
If someone can help me I would be greatful.
I added the following simple test method to UsersList class to demonstrate that the code is fine and you need to provide appropriate userNumber value when calling createUser method:
public static void main(String[] args) {
UsersList list = new UsersList();
int userNumber = 1;
list.createUser(userNumber); // insufficient length
System.out.printf("all nulls for %d? %s%n", userNumber, Arrays.stream(list.studentList).filter(Objects::isNull).count() == list.studentList.length);
userNumber = 123_456_789;
list.createUser(userNumber); // length of the number is 9
System.out.printf("no nulls for %d? %s%n", userNumber, Arrays.stream(list.studentList).filter(Objects::nonNull).count() == list.studentList.length);
}
Output:
all nulls for 1? true
no nulls for 123456789? true
However, you may want also to initialize the instance variable student.

Issue with thread safety- Not getting the answer expected

I am attempting to add up
a sequence of double precision floating point numbers which are given as Strings in an
array. The addition of these numbers is carried out in a separate background thread.
Running the code calculates the sum of the array of numbers and also gives the time that
the system took to calculate this in seconds.
I am not sure how to implement synchronization and conditional synchronization to this class:
public class SerialAdder implements Adder {
private String[] values;
private double sum;
private boolean ready = false;
public void run() {
synchronized (this) {
sum = 0.0;
for (int i = 0; i < values.length; i++) {
sum = sum + Double.valueOf(values[i]);
}
ready = true;
}
}
public synchronized void setValues(String[] values) {
this.values = values;
}
public synchronized void setThreads(int threads) {
// This does nothing since this is the single-threaded version.
}
public synchronized double getSum() {
return sum;
}
}
This should not be changed but is here for reference.
public interface Adder extends Runnable {
void setValues(String[] values);
void setThreads(int threads);
double getSum();
}
This is the main
import java.io.*;
public class Main {
/**
* All this data is "statistically initialized" and hence visibility to all threads in the running application.
*/
private static final String[] DATA1 = {"1.0", "2.0", "3.0", "4.0"};
private static final String[] DATA2 = {"100000000000000000000.0", "-100000000000000000000.0", "1.0", "2.0"};
private static final String[] DATA3 = {"1.0", "2.0", "100000000000000000000.0", "-100000000000000000000.0"};
/**
* This is an Example of more complex "static initialization" that guarantees data visibility to all threads.
*/
private static final String[] DATA4;
static {
/*** TASK3: CHANGE THIS VALUE SO THAT YOUR COMPUTER TAKES SEVERAL SECONDS FOR THE SERIAL CASE ***/
final int POWER = 10;
final int N = (int)Math.pow(2, POWER);
DATA4 = new String[N];
for (int i = 0; i < N; i++) {
DATA4[i] = String.valueOf(1.0/N);
}
}
public static void main(String[] args) throws InterruptedException, IOException {
// Start the timer ...
long startTime = System.currentTimeMillis();
/*** TASK 2 - CHANGE THIS LINE TO SEE HOW THE CODE BEHAVES WITH DIFFERENT DATA INPUTS. ***/
String[] values = DATA1;
/*** TASK 3 - CHANGE THE FOLLOWING SINGLE LINE TO CHANGE TO USING A MULTITHREADED VERSION OF THE ADDER. ***/
// This is an example of "programming to an interface" ... so only a single line
// needs to be changed to change the implementation used in the rest of the code.
Adder adder = new SerialAdder(); // = MultithreaderAdder();
adder.setValues(values);
new Thread(adder).start();
System.out.println("Answer = " + adder.getSum());
// Printed answer ... stop the timer.
long endTime = System.currentTimeMillis();
// Nanoseconds to seconds ...
System.out.println("Time = " + (endTime - startTime)/1000.0 + " seconds.") ;
}
}
And the multithreaded adder:
public class MultithreadedAdder implements Adder {
public void run() {};
public void setValues(String[] values) {};
public void setThreads(int threads) {};
public double getSum() {
return 0.0;
}
}
I am using the current data {“1.0”, “2.0”, “3.0”, “4.0”} and so expect answer of 10.0 however I am getting 0.
I would suggest some simplifications:
Drop the Adder interface. Implement the Callable interface instead. It allows you to return a value.
I'd advise against the setThreads() method. Give your Callable instance to a pooled Executor.
If one of those Strings in the array does not parse as a Double your sum will fail. What do you plan to do about it? I'd have a try/catch block.
import java.util.Arrays;
import java.util.concurrent.Callable;
public class DoubleStreamAdder implements Callable<Double> {
private final String [] values;
public DoubleStreamAdder(final String [] v) {
this.values = new String[v.length];
System.arraycopy(v, 0, this.values, 0, v.length);
}
#Override
public Double call() throws Exception {
return Arrays.stream(this.values).mapToDouble(Double::valueOf).sum();
}
}
You could do all of this using Java functional programming without the classes: see the single line in my call() method. That is what you're trying to do. The less code you write, the fewer bugs you'll have. You can eliminate more than 17 lines of code by deleting your interface and the class and writing a single line of code. Much better.

count the number of objects created by java

I'm trying to count the number of objects created but it always returns 1.
public class Drivertwo {
public static void main(String[] args) {
Employee newEmp = new Employee();
Employee newEmp2 = new Employee();
Calculate newcal = new Calculate();
Clerk newclerk = new Clerk();
float x;
int y;
newEmp.setEmp_no(2300);
newEmp.setEmp_name("W.Shane");
newEmp.setSalary(30000);
newEmp.counter();
newEmp2.setEmp_no(1300);
newEmp2.setEmp_name("W.Shane");
newEmp2.setSalary(50000);
newEmp2.counter();
newclerk.setEmp_name("Crishane");
newclerk.setEmp_no(1301);
newclerk.setGrade(2);
newclerk.setSalary(45000);
newclerk.counter();
System.out.println("Salary is:" + newcal.cal_salary(newclerk.getSalary(), newclerk.getEmp_no()));
System.out.println("Name is:" + newclerk.getEmp_name());
System.out.println("Employee number is:" + newclerk.getEmp_no());
System.out.println("Employee Grade is:" + newclerk.getGrade());
System.out.println("No of objects:" + newEmp.numb);
This is my class with the main method
public class Employee {
private int salary;
private int emp_no;
private String emp_name;
public int numb=0;
public int getSalary() {
return salary;
}
public int getEmp_no() {
return emp_no;
}
public String getEmp_name() {
return emp_name;
}
public void setSalary(int newSalary) {
salary = newSalary;
}
public void setEmp_no(int newEmp_no) {
emp_no = newEmp_no;
}
public void setEmp_name(String newEmp_name) {
emp_name = newEmp_name;
}
}
public int counter() {
numb++;
return numb;
This is my Employee class
I tried to run counter in my employee class as a starter but it always returns 1. I know I can make a counter in main class and everytime I make a new object I can get the counter but I want to automatically increase the numb by 1 when an object is made.
You need to make numb static so that there will only be one copy for every instance of the class. As it is, every single Employee object has its own copy of numb.
Also instead of creating a method to up the counter why not just put it in the constructor:
public Employee() {
numb++;
}
numb is an instance variable, meaning that each Employee object will have its own numb, that will be initialized by 0.
If you want all the Employee instances to share the same numb, you should make it static.
// Java program Find Out the Number of Objects Created
// of a Class
class Test {
static int noOfObjects = 0;
// Instead of performing increment in the constructor instance block is preferred
//make this program generic. Because if you add the increment in the constructor
//it won't work for parameterized constructors
{
noOfObjects += 1;
}
// various types of constructors
public Test()
{
}
public Test(int n)
{
}
public Test(String s)
{
}
public static void main(String args[])
{
Test t1 = new Test();
Test t2 = new Test(5);
Test t3 = new Test("Rahul");
System.out.println(Test.noOfObjects);
}
}
Since static members initialized only once and it will be same for each and every instances of class.
class YourClass {
private static int numb;
public YourClass() {
//...
numb++;
}
public static int counter() {
return numb;
}
}
So simple;-
make this modifications
make numb static like, public int numb=0;,
remove numb++; from method count() and
create constructor public Employee{numb++;}

Java inheritance ( local variable/ boolean in if)

I am studying the inheritance (Java), and I wrote the following code. The first part is the CarBase, and then I created a childclass 1, called Bus.
My idea is that first make a judgement if it is a bus, and by doing that, I need a boolean [if(isBus)], but when I wrote this code in Eclipse, there is a error message, said 'isBus can not be resolved to a variable'.
Could some one please tell me how to solve this problem? Do I need to declare the boolean variable first?
Another question is about the declaration of local variables.
In the getOnBus(0 method, I have a local variable called temp,I was taught that whenever using a local variable insided a method, I need to declare it first and then I shall be able to use it, but I saw someone use it directly like the following, I was wandering what's the difference between the two?
public class Bus extends CarBase {
//Unique bus properties
public int max_Passenger = 35;
public int current_Passenger = 0;
// unique bus method
public boolean getOnBus(int p_amount) {
if(isBus) {
int temp = 0; // <===
temp = current_Passenger + p_amount; // <===
if( temp > max_Passenger) {
return false;
} else {
current_Passenger = temp;
return true;
}
}
return false;
}
}
or if there is difference if I use it without declaring it?
public class Bus extends CarBase {
//Unique bus properties
public int max_Passenger = 35;
public int current_Passenger = 0;
// unique bus method
public boolean getOnBus (int p_amount) {
if(isBus) {
int temp=current_Passenger+p_amount; // <====
if( temp > max_Passenger) {
return false;
} else {
current_Passenger = temp;
return true;
}
}
return false;
}
}
The code is as following
First Part CarBase(parent)
public class CarBase {
public int speed;
public String name;
public String color;
public int maxSpeed = 90;
// Method
public void speedUp(int p_speed) {
int tempSpeed = 0;
if (p_speed > 0) {
tempSpeed = speed + p_speed;
}
if (tempSpeed <= maxSpeed) {
speed =tempSpeed;
}
}
}
Second Part Bus (Child1)
public class Bus extends CarBase {
//Unique bus properties
public int max_Passenger = 35;
public int current_Passenger = 0;
// unique bus method
public boolean getOnBus (int p_amount) {
if (isBus) {
int temp = 0;
temp = current_Passenger + p_amount;
if (temp > max_Passenger) {
return false;
} else {
current_Passenger = temp;
return true;
}
}
return false;
}
}
The point in using inherance is to abstract whether an object is a Car or a Bus, and write code that works no matter what is passed. To do so, you use abstract methods. Consider
abstract class Vehicle {
private int occupied;
public Vehicle() {
occupied = 0;
}
public abstract int getCapacity(); // number of passengers
public boolean board(int howmany) {
if (occupied+howmany <= capacity) {
occupied += howmany;
return true;
}
else
return false;
}
public void unboard(int howmany) {
occupied -= howmany;
}
};
class Car extends Vehicle {
public Car () { super(); } // just call the Vehicle() constructor
public int getCapacity() { return 5; }
}
class Bus extends Vehicle {
public Bus() { super(); } // just call the Vehicle() constructor
public int getCapacity() { return 32; }
}
you'd write every function to accept a Vehicle, and deal with it without the need to know if it is a bus or a car. (the following is a dumb function, just to give you an example)
void board_on_first_avaible(Vehicle[] x, int n) {
for (int i=0; i<x.length; x++)
if (x.board(n))
return true; // board ok
return false; // couldn't board on anything
}
Note that you should design your code so that the functions are declared, abstract in Vehicle, for both Car and Bus. Thus getOnBus() would be a bad idea
OK for the first point "isBus" is not declared, i can not see the point of checking in this method as you already know u are extending the CarBase but if you need to check you can do it like this
if(this instanceof CarBase)
for the second point there is actually no effect for the change
int temp=0; // <===
temp= current_Passenger+p_amount; // <===
first you initialize with 0 then you assign the new value to it
int temp=current_Passenger+p_amount;
here you initialize the temp with the value
You don't need to check if the Bus object 'isBus()' .... it IS a Bus, because you are defining the class as Bus!
So... if you were to create a new Bus object, you would say something like:
Bus BigYellowBus0001 = new Bus();
if you were to then say:
BigYellowBus0001.getOnBus(10);
You would NOT need to check if BigYellowBus0001 is a bus.... right?
In fact, you don't even need to name the method getOnBus().... it could just be getOn.
I think maybe you've gotten off on the wrong foot by deciding that Bus is a subclass of Car.
As for local variables, this just means variable that begin and end inside the method... so you did that nicely with your 'temp' variable.
To show that you understand how to access variables of the superclass from the child class, you could check the speed of the bus before letting people on:
public boolean getOnBus (int p_amount){
if(speed = 0){
int temp=0;
temp= current_Passenger+p_amount;
if( temp > max_Passenger){
return false;
} else{
current_Passenger = temp;
return true;
}
}
return false;
}
isBus is not declared that reason why you got this error
You doesn't need this check, because this method declared for Bus class and you are sure what it IS a Bus not a parent CarBase class (please use Vechicle instead of CarBase, it's much better on my opinion)
In Java 0 is default value for int, so you don't need to init variable before assign new value
So you can simplify getOnBus() like that
public boolean getOnBus (int p_amount) {
int temp = current_Passenger + p_amount;
if (temp > max_Passenger) return false;
current_Passenger = temp;
return true;
}
To test if an object is an instance of a class you can to use variable instanceof YourClass which evaluates to a boolean

Priority Queue add method modifies the all the elements with the last element added to it. Why?

/In hadoop reduce method I am adding TopFrequency objects to the PriorityQueue.
Assume that I have getTotalCount method present in my reducer class.
totalCount is an instance variable of type DoubleWritable./
class TopFrequency{
private double relativeFrequency;
private WordPair wordPair;
#Override
public int compareTo(TopFrequency arg0){
int i=this.wordPair.compareTo(arg0.wordPair);
if(this.relativeCount<arg0.relativeCount){
return -1;
}else if(this.relativeCount>arg0.relativeCount){
return 1;
}else if(this.relativeCount==arg0.relativeCount){
return 0;
}
return i;
}
}
class WordPair{
private Text word;
private Text neighbor;
}
class Reduce extends Reducer{
#Override
protected void reduce(WordPair key, Iterable values, Context context) {
double rCount=0.0;
int count = getTotalCount(values);
relativeFrequency=((double)count/totalCount.get());
relativeCount.set((double) count / totalCount.get());
//Creating an object of TopFrequency
TopFrequency topFrequency=new TopFrequency(key, relativeFrequency);
// All the references in reducerQueue point to recently added object
reducerQueue.add(topFrequency);
System.out.println("After adding to the queue "+reducerQueue);
}
}

Categories