What does immutability mean in the definition of the nCopies API in JAVA ?What is an use case for this API? [closed] - arraylist

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I came across a nCopies code somewhere and not being familiar with this funciton, I looked up the Oracle Docs and noticed that the definition says :
Returns an immutable list consisting of n copies of the specified object.
What does immutable to mean here ?I thought immutable meant that it cannot be modified. However, I notice that I am able to modify it . Also, I am able to reassign some other list to it.
This is the sample code I wrote to check the behavior .
public static void main(String[] args){
List<Integer> list = new ArrayList<>(Collections.nCopies(5,0));
List<Integer> list2 = new ArrayList<>();
list2.add(2);list2.add(3);
for(int i=0;i<list.size();i++){
int prod = i*2;
list.set(i, prod); // list is modifiable
}
print(list);
list = list2; // list is assignable
print(list);
}
What is an use case of this API ?

Try List<Integer> list = Collections.nCopies(5,0); - your version passes the immutable collection to the ArrayList(Collection<? extends E> c) constructor, which copies it. The copy is mutable.

Related

What does mutability of val objects mean in Kotlin? [duplicate]

This question already has an answer here:
Is the Kotlin term "mutable" wrong?
(1 answer)
Closed 1 year ago.
If val and var stands for immutability and mutability . The what does
val newList = mutableListOf(1,2,3) mean ?
Objects are reference values. So you have two things: newList is a val containing a reference to a mutable list. NewList cannot be changed to a reference to a different object.
The object that was created by “mutableListOf(1,2,3)” is stored somewhere in memory, and you can modify it. If you say remove the 3 and add a 4 you have the same object but with different contents. The reference stored in newList is unchanged and cannot be changed. It now references the same object, which now has items 1,2 and 4.

Create instance of anonymous class in kotlin [duplicate]

This question already has answers here:
How to create an instance of anonymous class of abstract class in Kotlin?
(2 answers)
Closed 2 years ago.
In C# I can:
var a = new { prop42 = "42" };
Console.WriteLine("a.prop42 = " + a.prop42);
Or do some other things, like serialization anonymous class instances (for using in js in browser). No interfaces or abstract classes used, fully anonymous class instance.
It is possible to make same thing in Kotlin?
Yes, you can do the equivalent in Kotlin:
val a = object { val prop42 = "42" }
println("a.prop42 = ${a.prop42}")
It's described in the language reference.  See also this question.
This isn't often a good idea, though.  Because the type doesn't have a name, you can't use it in public declarations, such as class or top-level properties of that type; nor can you create lists or maps of it.  (In general, you can only refer to its named superclass — Any in this case, since you didn't specify one.)  So its use is a bit restricted.  (The lack of a name also makes the code harder to follow.)

Unique number to be used as ID across all classes in VB.Net [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have an application that runs several asynchronous methods to create messages that are sent with a unique id to a remote host.
Two types of messages are being created in two separate classes. One class is inherited from the other but the shared methods are shadowed meaning they are different.
I would like the ID to be an incremented integer.
Does anyone have a good way of accomplishing this task? I have looked up the use of static numbers and class generated ids but they don't cover the shared method issue.
I am also aware of a single shared method being able to use a static number but that doesn't help when my method is shadowed.
You'll need some single-instance way of doing this.
VB.NET natural way would be using Module:
Module IDHelper
Private fLastID As Integer
Public Function NextMessageID() As Integer
Return Threading.Interlocked.Increment(fLastID)
End Function
End Module
Nice way of doing this is using singleton. Or somehing like that. But your original idea with shared member works as well. Problem could be in missing synchronization.
Public Class Base
Private Shared fLastID As Integer
Protected Function NextMessageID() As Integer
Return Threading.Interlocked.Increment(fLastID)
End Function
Public Function CreateMessage() As String
Return "Base message is " & NextMessageID()
End Function
End Class
Public Class Inherited
Inherits Base
Public Shadows Function CreateMessage() As String
Return "Inherited message is " & NextMessageID()
End Function
End Class
Shadowing functions is almost never a good idea. Overriding is the good way to go.
I figured it out. I needed the ID to also be shared so it would share across all classes too instead of my two methods generating the ID independently and being aware of the others current ID number.
Code
Public Property MessageID As Long
Private Shared NextID As Long = 0
Public Shared Function GenerateNextID() As Long
NextID += 1
Return NextID
End Function

Loading from database - inside or outside class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've seen different ways of loading an object to and fro a database, with two common ones as shown below. Which one is better, and why?
Method 1: This includes defining two member methods for a class, load(id) and save(). These methods are called on instances of the class. For example,
class Wheel{
double diameter;
string tag;
public void Load(int id){
var result = ... // database query
this.diameter = result['diameter'];
this.tag = result['tag'];
}
public void Save(){
... // database query to update row
}
}
Wheel johnWheel = new Wheel();
johnWheel.Load(5); // In this case John's wheel has a row id of 5 in the database
Method 2: A utility method which loads/saves an object directly:
class DBUtils{
public static Wheel LoadWheel(int id){
var result = ... // database query
Wheel w = new Wheel();
w.setDiameter(result['diameter']);
w.setTag(result['tag']);
}
public static void SaveWheel(Wheel wheel){
...// Update DB
}
}
I ask because the notion of a 'wheel' itself does not include functions which loads and saves it from a database, so perhaps method 1 would be considered bad OOP design.
Both seem a bit off...
Method 1
For one thing, Load() should be a static factory in this case. This usage is a bit obtuse:
Wheel johnWheel = new Wheel();
johnWheel.Load(5);
Between those two lines of code, what is johnWheel? Is it in anything approaching a valid state? If not, then it seems like its construction is a little broken. OO principles would suggest encapsulating that into a single operation rather than expecting consuming code to perform multiple sequential operations every time. If it's a static factory, the usage is simpler:
Wheel johnWheel = Wheel.Load(5);
Method 2
This one is more of a naming concern than a structure concern. DBUtils? That's going to turn into a dumping ground for unrelated functionality quickly. You want to avoid that. How about something like this?:
class WheelRepository
{
public static Wheel Get(int id)
{
// ...
}
public static void Save(Wheel wheel)
{
// ....
}
}
As an object (this is still OOP after all), a WheelRepository represents (and therefore encapsulates) very specific functionality whereas a DBUtils doesn't.
Conclusion
I generally prefer method 2 in a structural sense, because the business object (Wheel) shouldn't know anything about the database (WheelRepository). The former is a core portable business concern, the latter is a periphery infrastructure concern. My only caveat is that I'd recommend standard patterns for improving method 2, such as a combination of the Repository Pattern and the Unit Of Work pattern, for example.
You should create a separate class that handles database connections and the creation/destruction of these connections. That way, the wheel is a separate entity from the database it is using.
Go with method 2.
I would go with Method 2 (like laiello proposed). I would however not name the class DbUtils but more something like WheelDao or WheelRepository (if for instance your Wheel class is an Root entity in your domain model).
If however you go with Method 1 the load(id) method should be static. Since it is not called on a particular instance of an object but it rather produces a new instance of an object. This is unlike the save() method for which it is correct to be called on a specific instance of Wheel.

Best pratice when choosing between objects [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
So i am creating a program that collects alot of different data from the database and creats / updates several charts for the end user to see.
Now at some level all of the data follows the same pattern:
Every data has a date attached to it this date is used to display the X Cordinate on the chart
Every data has a so called queue (which is simply a name)**
Now what i have done so far is to create a super class (abstract class). My idea was to create individual sub classes of this super class and allow them to have their own implementation and fields.
Now to my question some of these objects will be relativly small for example i have an object that only consists of three fields with getter and setter. Is best pratice to devide and conquere or have as few objects as possible?
The alternative to having small objects is that a larger object that in short are talking the same type of object but half of them has a field that the other half does not I.E why i wanted to split it into two objects to avoid having a field that will be null 50% of the times.
Here is an example of how my objects look:
Example on subclass
class Callback : ContactQueue
{
public int completedCallbacks{get; set;}
public int completed_within_timeframe{get; set;}
public int answerPercentage { get; set; }
public override String type {get; set;}
public override DateTime period { get; set; }
public Callback(String type,DateTime period)
{
this.type = type;
this.period = period;
}
public override String toString()
{
return type;
}
public double percentageCompleted {
get
{
return completed_within_timeframe / completedCallbacks * 100; // todo
}
}
}
I hope you can understand my question if not please leave a comment and i will respond as soon as possible
It really depends on your system. If you want to have a storage for your fields then you can have one object with many getters/setters.
But I would recommend splitting them by behaviour. You might want to add methods to your objects and there will be differences in behaviour you'll want to have. And at this point if you had gone with the first way, you'll have to make a lot of checks inside these methods to correctly execute it. You need to separate objects to scale easier.