Reputation: 1637
I have an array of elements. I am making object on the basis of each elements name and call some getter functions. The object of the class that i am making is actually a third party library, "Sigar".
The problem is i don't want to modify this third party library, because of which i am not able to keep variables values separate for each object. I need come up with some way to keep separate variable separate for each object.
I hope my description explains what i want. Following is my code
private long lastDiskCheck = 0;
private long lastDiskRead = 0;
private long lastDiskWrite = 0;
private String getDiskUsage() {
try {
List<FileSystem> result = new ArrayList<FileSystem>();
org.hyperic.sigar.FileSystem[] fss = null;
fss = sig.getFileSystemList();
List<Integer> diskUsage = new ArrayList<Integer>();
String ioStat = "";
for (int i = 0; i<fss.length; i++) {
FileSystem fs = fss[i];
FileSystemUsage usage = sig.getFileSystemUsage(fs.getDirName());
if (lastDiskCheck!=0) {
long diff = (nanoTime() - lastDiskCheck)/1000000;
long diffRead = usage.getDiskReadBytes() - lastDiskRead;
long diffWrite = usage.getDiskWriteBytes() - lastDiskWrite;
ioStat = String.format("(%d/%d kB/s)", diffRead/diff, diffWrite / diff);
}
lastDiskRead = usage.getDiskReadBytes();
lastDiskWrite = usage.getDiskWriteBytes();
lastDiskCheck = nanoTime();
diskUsage.add((int)(usage.getUsePercent()*100));
}
return String.format("%d%% %s", (Collections.max(diskUsage)), ioStat);
} catch (SigarException e) {
e.printStackTrace();
}
return "n/a";
}
the three variables
private long lastDiskCheck = 0;
private long lastDiskRead = 0;
private long lastDiskWrite = 0;
updates for each object inside the loop which i don't want. How can i keep it different for each object?
Upvotes: 0
Views: 103
Reputation: 495
Well, in your case. You should study the 4 pillars of Object Oriented Programming in Java: http://learn2geek.com/4-pillars-oop-java/
After that, you understand how to create different instances and if you have a programming knowledge, you will not have any problem.
Moreove, to clarify and answer your problem. The best solution is to create a class with private attributes. You will access these attributes with getters/setters methods (public modifier). Indeed, you could create some objects and you could introduce and receive values of each object with the getters and setters.
Brief explanation: How do getters and setters work?
Upvotes: 1
Reputation: 1036
public class MyClass {
private long lastDiskCheck;
private long lastDiskRead;
private long lastDiskWrite;
private YourObject object;
public void setLastDiskCheck(lastDiskCheck){ // setter of lastDiskCheck
this.lastDiskCheck = lastDiskCheck;
}
public long getLastDiskCheck(){ //getter of lastDiskCheck
return lastDiskCheck;
}
}
With this methodology, you can keep each object in your MyClass and keep different value for each.
Upvotes: 1