Deep copy of an ArrayList <Integer> - arraylist

I'd like to copy the ArrayList zf into the ArrayList copyzf. The copy has to be a deep one.
I already tried:
public class ZFW {
Integer zfw;
public ZFW copy() {
ZFW m= new ZFW();
m.zfw=this.zfw.copy();
return m;
}
}
and in the executing code:
for(int r=0; r<zf.size();r++) {
Integer z;
z=zf.get(r);
copyzf.set(r, z.copy());
}
The error "The method copy() is undefined for the type Integer" occurs. I can't change the data type of the ArrayLists, does anybody know how I can solve the Problem? Thanks in advance!

Integers are immutable, so a deep copy is useless. Where in your code is the mentioned ArrayList?

Related

How to overload a function when you only need to change a parameter data type

I have a function SelectNext() that takes a collection parameter (of type IEnumerable) and it selects the next item in the collection and return that item.
'BaseListTypes is an Enum
Function SelectNext(listType As BaseListTypes, lst As IEnumerable(Of Object)) As Object
Dim res As Object
'function body here....
Return res
End Function
The above function works great for any List(Of T) where T is an object or string.
However it fails when I pass it a List(Of My_STRUCTURE) (custom structure I have, which contains 3 string variables)
Obviously since Structure is like integer and other base types are a value types.
While objects are reference types. I can see why I am getting an error at runtime.
My question is, is there a better way than just overloading my function into something like:
Function SelectNext(listType As BaseListTypes, lst As IEnumerable(Of My_STRUCTURE)) As Object
You can go with generic impelementation like SelectNext<T>
class Program
{
Program()
{
//SelectNext_Old(new List<object>(0)); it works
//SelectNext_Old(new List<Point>(0)); id doesn't work
SelectNext(new List<object>(0));
SelectNext(new List<Point>(0));
}
public object SelectNext_Old(BaseListTypes listType, IEnumerable<object> lst)
{
return null;
}
public object SelectNext<T>(BaseListTypes listType, IEnumerable<T> lst)
{
return null;
}
}
I dont know VB but I guess you can get the idea!
In theory, this should work for any type, whether it be reference type or value type:
Function SelectNext(Of T)(listType As BaseListTypes, lst As IEnumerable(Of T)) As T
Dim res As T
'function body here....
Return res
End Function
I'd need more information to know for sure though. Your question is actually a bit vague. For one thing, what does "selects the next item in the collection" actually mean? You should edit your question to make it more complete, with a better description of what you're doing and what errors occur and where.

A C function pointer cannot be formed from a local function that captures context

I get the following error for the code below: "A C function pointer cannot be formed from a local function that captures context."
Does anyone propose a creative solution to populate x in this example? I'm stumped. The underlying types for _header and _int respectively are UnsafePointer<mach_header>? and Int
import MachO
class Example {
func test() {
var x: [Int] = []
_dyld_register_func_for_add_image { (_header, _int) in
x.append(_int)
}
}
}
You could make x a static variable so it is accessible from anywhere and not depending on context. But it depends on your use case whether this works.

Class Methods: Passing private data fields in private methods

I was wondering if which of the following patterns are considered to be more "correct".
The first example sets the value of private data member length by calling a void member function that implicitly takes arguments.
The second example sets the value of length by assigning it to the return value of the member function that explicitly takes an argument.
It seems that the second method makes the code clearer, since you know when and how the private member is getting set,
where the first requires a trace of the code to verify what and how a value is being assigned. The second method
also seems like it would allow for better reuse down the road because it could operate in any class/context (since the
arguments and return type are explicit).
The first method is quicker, and if used throughout the entire class (for private member functions) can save some coding, however I'm
not sure if this will bite me down the road ?
Thank you for the insight and clearing this up for me.
class MyDataType
{
private int length;
private string content;
private char[] buffer;
public MyDataType(str)
{
content = str;
calculateLength();
buffer = new char[length+1];
for(int i=0; i < length; i++)
buffer[i] = content[i];
buffer[i] = NULL;
}
private void calculateLength()
{
int i = 0;
while(content[i++] != NULL) {} // i know, buffer overflow...
length = i;
}
}
class MyDataType
{
private int length;
private string content;
private char[] buffer;
public MyDataType(str)
{
content = str;
length = calculateLength(content);
buffer = new char[length+1];
for(int i=0; i < length; i++)
buffer[i] = content[i];
buffer[i] = NULL;
}
private int calculateLength(string s)
{
int i = 0;
while(s[i++] != NULL) {}
return i;
}
}
In terms of readability and flexibility the second example wins out.
The advantage to using the second example is that you are essentially just delegating some work in the constructor to a method. This is easy to read and won't easily break in the future if, for instance, someone calls the private calculateLength() method without expecting the instance variables to change.
In the first example the calculateLength() method is operating on the member variables in a non-transparent way to the constructor which makes it less readable and more prone to be brittle in the way described above.
I would say the second is more appropriate, but the first works.
Usually getters are public, anywhere within a class you can access a private variable, doesn't make sense to have a getter that gets a private or protected variable in the same class. If it were protected and you could pass functionality to subclasses of your class.
It depends on what you want to do with the variable. If the value isn't going to change, I would just move the private calculateLength() method to the constructor. If you have to recalculate it then I guess I can see either the void or private doing pretty much the same thing. I feel that the second is clearer because you know exactly where the calculateLength() method is returning, but in the first it it is ambiguous to whether it is doing anything at all. It's better style to do the second.
Why not embed the getLength() function content into the constructor, and do the copying simultaneously? You will save yourself another loop.
Other than that, I am pretty sure it does not matter much. Just go with the flow, start with a method, and then modify in the future if you see fit.

SafeArrayPutElement method throws System.AccessViolationException

I am trying to pass an array of ints from C# to C++/CLI. Here's my code:
// SafeArrayTesting_PlusPlus.cpp
#include "stdafx.h"
#include <comdef.h>
using namespace System;
namespace SafeArrayTesting_PlusPlus
{
public ref class MyCppClass
{
public:
MyCppClass();
~MyCppClass();
void SetMyInts(array<int>^ myInts);
};
MyCppClass::MyCppClass(){}
MyCppClass::~MyCppClass(){}
void MyCppClass::SetMyInts(array<int>^ myInts)
{
// Create safearray
SAFEARRAY *safeArrayPointer;
SAFEARRAYBOUND arrayDim[1]; // one dimensional array
arrayDim[0].lLbound= 0;
arrayDim[0].cElements= myInts->Length;
safeArrayPointer = SafeArrayCreate(VT_UNKNOWN,1,arrayDim);
// copy ints to safearray
for (long lo= 0; lo < myInts->Length; lo++)
{
cli::pin_ptr<int> pinnedIntPointer = &(myInts[lo]);
SafeArrayPutElement(
safeArrayPointer,
&lo,
static_cast<void*> (pinnedIntPointer)); // line XX
}
// do something with the safearray here
}
}
// SafeArrayTesting_Main.cs
using SafeArrayTesting_PlusPlus;
namespace SafeArrayTesting_Main
{
class SafeArrayTesting_Main
{
static void Main()
{
var myCppClass = new MyCppClass();
myCppClass.SetMyInts(new[]{42});
}
}
}
When I run this, line XX throws the following exception:
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I have a feeling that I'm doing something basically wrong with the SafeArrayPutElement method. Can you spot the error?
(By the way, I have asked a more complex variation of this question at Passing an array of interfaces from C# to C++/CLI . I think the difference is big enough to warrant two separate questions.)
safeArrayPointer = SafeArrayCreate(VT_UNKNOWN,1,arrayDim);
That creates an array of IUnknown interface pointers. SafeArrayPut() makes sure to increase the reference count of the interface pointer by calling IUnknown::AddRef() since it stores a copy of the pointer in the array.
You can see how that goes kaboom. Create an array of integers instead. Fix:
safeArrayPointer = SafeArrayCreate(VT_I4,1,arrayDim);

What is the difference between an Iterator and a Generator?

What is the difference between an Iterator and a Generator?
An iterator traverses a collection one at a time.
A generator generates a sequence, one item at a time.
You might for example, iterate over the result of a generator...
Generators are iterators, but not all iterators are generators.
An iterator is typically something that has a next method to get the next element from a stream. A generator is an iterator that is tied to a function.
For example a generator in python:
def genCountingNumbers():
n = 0
while True:
yield n
n = n + 1
This has the advantage that you don't need to store infinite numbers in memory to iterate over them.
You'd use this as you would any iterator:
for i in genCountingNumbers():
print i
if i > 20: break # Avoid infinite loop
You could also iterate over an array:
for i in ['a', 'b', 'c']:
print i
There's too much Python here, and too many people saying generators are the only way to implement an infinite iterator. Here's the example I mentioned (squares of all natural numbers) implemented in C#. ExplicitSquares explicitly implements an iterator (called IEnumerator in C#). ImplicitSquares uses a generator to do the same thing. Both are infinite iterators and have no backing collection. The only difference is whether the state machine is spelled out, or alternatively a generator is used.
using System.Collections;
using System.Collections.Generic;
using System;
class ExplicitSquares : IEnumerable<int>
{
private class ExplicitSquaresEnumerator : IEnumerator<int>
{
private int counter = 0;
public void Reset()
{
counter = 0;
}
public int Current { get { return counter * counter; }}
public bool MoveNext()
{
counter++;
return true;
}
object IEnumerator.Current { get { return Current; } }
public void Dispose(){}
}
public IEnumerator<int> GetEnumerator()
{
return new ExplicitSquaresEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
class ImplicitSquares : IEnumerable<int>
{
public IEnumerator<int> GetEnumerator()
{
int counter = 1;
while(true)
{
int square = counter * counter;
yield return square;
counter++;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class AllSquares
{
private static readonly int MAX = 10;
public static void Main()
{
int i = 0;
foreach(int square in new ExplicitSquares())
{
i++;
if(i >= MAX)
break;
Console.WriteLine(square);
}
Console.WriteLine();
int j = 0;
foreach(int square in new ImplicitSquares())
{
j++;
if(j >= MAX)
break;
Console.WriteLine(square);
}
}
}
A generator is an implementation of an iterator. It is typically a routine that yields multiple values to its caller as opposed to just one.
In c#
// yield-example.cs
using System;
using System.Collections;
public class List
{
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while (counter++ < exponent)
{
result = result * number;
yield return result;
}
}
static void Main()
{
// Display powers of 2 up to the exponent 8:
foreach (int i in Power(2, 8))
{
Console.Write("{0} ", i);
}
}
}
See Wikipedia's entry
A Generator is a special function that can behave as an Iterator, returning a value each time it is called. Because it is a function, it can compute each value on demand. And because it is special, it can remember its state from the last time it was called, so the resulting code looks pretty simple.
For example, this generator in python will produce a sequence of integers
def integers():
int n = 0
while True:
yield n
n += 1
The important thing in this example is the yield n statement. The function will return the value, and the next time it is called, it will continue from that point.
This link has a longer explanation of generators in python:
link text
(from javascript useland, yet same as all others)
An interator is an object that has a .next() function
A generator is a function, once invoked, produce an iterator, it's a factory for iterator.
In javascript, generator function require a special syntax function *(){} and the use for the yield keyword
See MDN on this : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators
An iterator is used to iterate over the objects in a collection, be that an array, linked list, tree, hash map, whatever. You've got a bunch of objects and you want to do something with each one of them.
A generator doesn't just return the items from some finite collection of objects. Instead, it generates them on the fly. You could conceptualize it as an iterator over a collection that is created while you are iterating over it and may not have finite size.
For instance, you could have a generator that spits out prime numbers from 2 to infinity. There's no way you could have a collection of "all prime numbers" and iterate over it with an iterator. You need a generator.
Or you could have a generator that takes an integer and yields the factors of that number one at a time. A generator would benefit you here as you could examine the factors one by one without allocating memory for all of the factors upfront. It would also allow you to use them as they are generated rather than having to generate the entire list up front, which might be slower than you like. Here's an example of such a generator in Python:
def factors(n):
for i in xrange(1, n+1):
if n % i == 0:
yield i
for n in factors(1234567890):
print n
If you run this you can see the factors printed as they are calculated. We don't need to actually maintain an entire list of all factors in memory.
Usually iterators walk over an existing sequence (such as an array or list) and generators calculate a new value upon every request.
An iterator is commonly used to move through a collection of items. Often having MoveNext() and Current() methods. MoveNext() would shift the pointer to the next collection item (if possible) and return true/false based on success. Current() would provide the actual value.
A generator is an implementation of iterator, but instead of pointing to a pre-existing collection, it creates new items on each MoveNext() call.
Easy to understand definitions are:
Iterator is an object iterating a list of items.
Generator is a function generating an iterator.
Generator iterator is an iterator generated by generator.
Popular yet confusing definitions are:
Iterator is an object iterating a list of items.
Generator function is a function generating an iterator.
Generator is an iterator generated by generator function.