Possible to sort generic linked list in Java? - cluster-analysis

I'm trying to implement a k-means clustering algorithm (although that detail is not particularly important), and I wanted to make it work using generics in Java.
So in my main class I will call a cluster method. I was wondering if something like the following would be possible:
public static <T> void cluster(int k, LinkedList<T> list) {
// Sort the list
LinkedList<T> sortedList = Collections.sort(list);
...
}
Obviously the problem that I am running into is that T cannot be guaranteed to implement Comparable... But is there any way to achieve what I am trying to do?

This should work:
public static <T extends Comparable<T>> void cluster(int k, List<T> list) {
Collections.sort(list);
...
}
The <T extends Comparable<T>> makes sure that the List<T> holds Comparable<T> elements.
I used List<T> because the implementation (LinkedList, ArrayList etc.) doesn't matter - you access it via the List interface. But you can use LinkedList<T> instead if that's what you need.
And, Collections.sort() doesn't return anything, it sorts in-place.

Related

Generic builder of (almost) identical 3rd party classes

I have a bunch of 3rd party classes, these classes are autogenerated in java and do not have any hierarchy
Here is the RulesPropertyList
enum RulesPropertyType {...}
class RulesPropertyValue {...}
class RulesProperty {
public RulesPropertyType getPropertyTypeCode(){...}
public RulesPropertyValue getPropertyValue() {...}
}
class RulesPropertyList {
public void setNumProperties(int numProperties)
public void setProperties(RulesProperty[] properties)
}
And its Characs* sibling
enum CharacsPropertyType {...}
class CharacsPropertyValue {...}
class CharacsProperty {
public CharacsPropertyType getPropertyTypeCode(){...}
public CharacsPropertyValue getPropertyValue() {...}
}
class CharacsPropertyList {
public void setNumProperties(int numProperties)
public void setProperties(CharacsProperty[] properties)
}
There are more than just Rules* and Characs* families of classes, and classes actually have more fields and deeper structures.
All classes are completely identical except for the prefixes in the class names.
Currently, I have a separate builder method for each set of classes.
def buildRulesPropertyList(props: (RulesPropertyType, RulesPropertValue): RulesPropertyList = {
val properties = props.map { case (type, value) =>
RulesProperty(type, value)
}
val propList = RulesPropertyList
propList.setProperties(properties.toArray)
propList.setNumProperties(properties.length)
propList
}
I have to create such a builder for each family of classes.
Now I only see a possibility to make a generic builder using reflection.
Is there a way in Scala to make such a builder using generics in Scala language?
Is there a way in Scala to make such a builder using generics in Scala language?
yes, but I don't think it's going to be any less code. I think your best move here is to just write some simple code generation for each type. you would feed it a list of family names like Seq("Rules", "Characs", ...) and have it spit out your build${family}PropertyList methods.

How to use a C++ class with pure virtual function?

I was given a class with pure virtual function like the following:
class IRecordingHour{
public:
virtual int getData() const = 0;
}
Now, I have another class that uses the IRecordingHour class:
class ProcessRecordingHours {
public:
ProcessRecordingHours (IRecordingHour &);
proteted:
IRecordingHour & recordingHour;
}
I was told that I am not allowed to implement the IRecordingHour class (the one with the pure virtual function).
My question is: without implementing the IRecordingHour clas, how do I use it in the ProcessingRecordingHours? That is, how do I create an instance of the IRecordingHour and pass it to the constructor of the ProcessRecordingHours?
You should create a subclass of IRecordingHour and implement the method getData, like
class ARecordingHour : public IRecordingHour
{
public:
int getData() const override //override is valid from C++11
{
return 42;
}
}
And then you can do:
ARecordingHour arh{};
ProcessRecordingHours prh{arh}; //{}- Modern C++ initialization
You can find similar examples in a good C++ programming book, such as The C++ Programming Language
Though you equate them, your two questions are in fact quite different.
how do I use it in the ProcessingRecordingHours?
There is no particular problem in implementing ProcessingRecordingHours without implementing a subclass of IRecordingHour. You don't need to do anything special. You simply avoid relying on anything not declared by IRecordingHour, which is no different than you ought to do anyway.
how do I create an instance of the IRecordingHour and pass it to the constructor of the ProcessRecordingHours?
You cannot. A class with a pure virtual method cannot be directly instantiated. Your ProcessRecordingHours can be used in conjunction with classes that extend IRecordingHour, but if you are not permitted to create such a class then you cannot exercise those parts of your ProcessRecordingHours class that depend on an IRecordingHour.
Perhaps, however, you have misunderstood the problem. You may be forbidden from implementing IRecordingHour::getData(), but not from implementing a subclass that overrides that method with a concrete one. Such a subclass could be instantiable, and would be usable in conjunction with ProcessRecordingHours.
I think your teacher plan to inject an implementation of IRecordingHour into ProcessRecordingHours.
Also, you can't use that class unless you generate a stub for IRecordingHour or you implement one yourself with some dummy return values.
/// <summary>
/// in C# and interface can only contain virtual methods. so no need to say virtual.
/// </summary>
interface IRecordingHour
{
int getData();
}
class MockRecordingHour : IRecordingHour
{
public int getData()
{
//just return something. This will be enough to get ProcessRecordingHours to work
return 100;
}
}
/// <summary>
/// this class expects a IRecordingHour.
///
/// how we get a IRecordingHour depends on who's implementing it. You, some 3rd party vendor or another developer who's using this class that you've written.
///
/// Oh wait. Since you're building ProcessRecordingHours, you need a IRecordingHour to get against. You can use a mocking tool or create one yourself that returns some dummy data
/// </summary>
class ProcessRecordingHours
{
private IRecordingHour _recording;
public ProcessRecordingHours(IRecordingHour recording)
{
this._recording = recording;
}
public void DoSomething() {
Console.WriteLine("Recording Data: {0}", this._recording.getData());
}
}

How to enrich a Java library class that has static methods (aka enrich an object in Scala)?

I'm trying to extend a class (SWT.java) from a Java library (SWT) that only has static final members. An excerpt from the library class:
package org.eclipse.swt;
import org.eclipse.swt.internal.*;
public class SWT {
public static final int None = 0;
// ...
public static final int MouseDown = 3;
// ...
}
My Java wrapper class that worked fine in Java land:
public class SWT extends org.eclipse.swt.SWT {
public static final int FinalizeText = 201;
public static final int ParseText = 202;
}
Now if I try to use my new SWT class in Scala, I'll get errors like this:
Error:(198, 27) value MouseDown is not a member of object my.package.SWT
table.addListener(SWT.MouseDown, periodEditListener)
^
Ideally I would like a new SWT object with which I could access both original members (e.g. MouseDown) and members I define (e.g. FinalizeText).
It seems that Scala interprets everything useful about this class as an object, which is fine if we just want to use the original SWT definitions, but you can't easily extend objects in Scala.
It has occurred to me that implicits a la pimp my library might be the way to go, but even were I to get this to work, I think the solution would not be accessible from Java (still, I have not even gotten in to work in Scala).
How to best tackle the problem? Maybe the right answer is to just define a separate, unrelated object.
I don't think there is a good way to do what you want such that:
You can neatly tie all members to an identifier (i.e. refer to the field via SWT.X instead of X)
Have it work both in Scala and Java.
You don't have to manually forward fields.
This is a documented limitation of Scala -- see access java base class's static member in scala.
In addition, I don't think the implicit route works either, because you can't treat a Java class as a value: How to access a Java static method from Scala given a type alias for that class it resides in
Probably the best way to do what you want is to manually forward the static members you need in my.package.SWT:
public class SWT extends org.eclipse.swt.SWT {
public static final int FinalizeText = 201;
public static final int ParseText = 202;
public static int getMouseDown() {
return MouseDown;
}
}
If you only care about automatically forwarding members and not about the other requirements, you can use import:
import org.eclipse.swt.SWT._
table.addListener(MouseDown, periodEditListener)
I am accepting yuzeh's answer for thoroughness, general applicability, and helpfulness, but here is what I actually did, which is slightly different:
I was very tempted by yuzeh's last suggestion for the sake of uniformity, i.e.
import org.eclipse.swt.SWT._
import my.package.SWT._
Although as my first example snippet above inadvertently shows, SWT.None unfortunately is, so bringing it into the local namespace would conflict with Option's None.
I think for now I'll just import like:
import org.eclipse.swt.SWT
import my.package.{SWT => MySWT}
If nothing else, it is a bit more clear where the constants are coming from. There, I talked myself into believing this is better :).

Wrapping JavaScriptObjects in case of multiple subclasses?

I have a bunch of data entities that all implement Entity. Now I want to expose some of these entities to JavaScript code, but I can't just make a bunch of JavaScriptObject subclasses because of the one-implementation rule.
So, I'm using this kind of thing:
public class JsStandardScale3 implements StandardScale3 {
private JavaScriptObject wrapped;
public JsStandardScale3(JavaScriptObject wrapped) {
this.wrapped = wrapped;
}
#Override
public native Long getLicenseId() /*-{
this.#com.activegrade.client.exported.JsStandardScale3::wrapped.getLicenseId();
}-*/;
This works, it's just a lot of work. The overlay type structure is so much nicer. Any suggestions?
It turns out that you CAN extend JavaScriptObject with multiple subclasses of an interface as long as all of your extensions are from a single "root" extension of JSO.
For example, I have the structure Standard extends Entity and Course extends Entity. I could NOT do:
JsStandard extends JavaScriptObject...
JsCourse extends JavaScriptObject...
but I could do:
JsEntity extends JavaScriptObject...
JsStandard extends JsEntity...
JsCourse extends JsEntity...
fantastic!
The only limitation is that every method must be marked final, which works fine for a simple overlay scenario.

Autofac: Injected collection is not empty (contains one item)

I'm using Autofac 2.4.4.705.
The output of the following code is: 1 (which means the resolved collection contains one item. I thought it should be empty)
class Program
{
static void Main(string[] args)
{
var builder = new Autofac.ContainerBuilder();
builder.RegisterModule(new AutofacModule());
using (var container = builder.Build())
{
var x = container.Resolve<ObservableCollection<A>>();
Console.WriteLine(x.Count);
}
}
}
class A
{
}
class AutofacModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());
builder.RegisterGeneric(typeof(ObservableCollection<>))
.As(typeof(ObservableCollection<>));
}
}
It seems the issue is cause by:
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());
If I remove it from AutofacModule, then the output is 0.
Any ideas?
Thanks
Update:
Ah, I think I understand now. Autofac thought I want to resolve all types of A, and there is one type of A in this example (A itself), so the ObservableCollection contains one item. I previously thought only IEnumerable<> has this behavior. But it seems subtypes of IEnumerable<> also have this behavior.
But sometimes what I really want is to inject an collection, for example, sometime I need to inject DispacherNotifiedObservableCollection into my ViewModels. Any workarounds?
Update 2:
Based on the answer of Nicholas Blumhardt, I changed my code to:
builder.RegisterGeneric(typeof(ExtendedObservableCollection<>))
.As(typeof(IObservableCollection<>))
.UsingConstructor();
public interface IObservableCollection<T> :
IList<T>, ICollection<T>, IEnumerable<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
void AddRange(IEnumerable<T> list);
void Sort<TKey>(Func<T, TKey> keySelector, System.ComponentModel.ListSortDirection direction);
void Sort<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer);
}
Now everything works fine. Thanks!
The behavior you're seeing is a result of the ObservableCollection type having a constructor that accepts IEnumerable.
You can change this to use the default constructor using the UsingConstructor() option.
ObservableCollection itself might not be a very good contract to depend on though- it is a bit unclear what the semantics should generally be. Wrapping it in a specialized component with it's own interface is the better option.